ExecuteScalar throws NullReferenceException - asp.net

This code throws a NullReferenceException when it calls ExecuteScalar:
selectedPassengerID = 0;
//SqlCommand command = GenericDataAccess.CreateCommand();
// 2nd test
string connectionString = "";
SqlConnection conn;
connectionString = ConfigurationManager.
ConnectionStrings["ConnST-MHM"].ConnectionString;
conn = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.StoredProcedure ;
command.Connection = conn;
command.CommandText = "SearchForPassenger";
SqlParameter param;
param = command.CreateParameter();
param.ParameterName = "#name";
param.Value = pName; // Session[""];
param.DbType = DbType.String;
command.Parameters.Add(param);
param = command.CreateParameter();
param.ParameterName = "#flightDate";
param.Value = date;
param.DbType = DbType.String;
command.Parameters.Add(param);
param = command.CreateParameter();
param.ParameterName = "#ticketNo";
param.Value = ticketNumber;
param.DbType = DbType.Int32;
command.Parameters.Add(param);
int item;
command.Connection.Open();
item = (int)command.ExecuteScalar();

I have encapsulated most of my SQL logic in a DAL. One of these DAL methods pulls scalar Ints using the following logic. It may work for you:
object temp = cmnd.ExecuteScalar();
if ((temp == null) || (temp == DBNull.Value)) return -1;
return (int)temp;
I know that you have entered a lot of code above but I think that this is really the essence of your problem. Good luck!

ExecuteScalar returns null if no records were returned by the query (eg when your SearchForPassenger stored procedure returns no rows).
So this line:
item = (int) command.ExecuteScalar();
Is trying to cast null to an int in that case. That'll raise a NullReferenceException.
As per Mark's answer that just poppped up, you need to check for null:
object o = command.ExecuteScalar();
item = o == null ? 0 : (int)o;

Related

Stored procedure with input & output parameters and 2 recordsets

I try to extract the results in c# asp.net from my stored procedure but it has 2 recordsets. the first with 1 row and the second with many rows as dates.
The code
public string penth_slqDAYS(string connectionString)
{
string sMonth = DateTime.Now.Month.ToString();
string syear = DateTime.Now.Year.ToString();
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command1 = new SqlCommand("penthhmera_proc", connection);
/////////////////////////////
SqlParameter param1;
param1 = command1.Parameters.Add("#prs_nmb_pen", SqlDbType.VarChar, 7);
param1.Value = prs_nmb_lb1.Text.Trim();
SqlParameter param2;
param2 = command1.Parameters.Add("#month_pen", SqlDbType.Int);
param2.Value = sMonth;
SqlParameter param3;
param3 = command1.Parameters.Add("#year_int", SqlDbType.Int);
param3.Value = syear;
/////////////////////////
command1.Parameters.Add("#days_out", SqlDbType.Int);
command1.Parameters["#days_out"].Direction = ParameterDirection.Output;
command1.Parameters.Add("#message_out", SqlDbType.VarChar,50);
command1.Parameters ["#message_out"].Direction = ParameterDirection.Output;
command1.Parameters.Add("#dateess_out", SqlDbType.Date);
command1.Parameters["#dateess_out"].Direction = ParameterDirection.Output;
///////////////////////////
connection.Open();
command1.CommandType = CommandType.StoredProcedure;
command1.ExecuteNonQuery();
days_penthwork_tx.Text = Convert.ToString(command1.Parameters["#days_out"].Value);
message_tx.Text = Convert.ToString(command1.Parameters["#message_out"].Value);
///the above parameter contains rows with dates
Label12.Text = Label12.Text + Convert.ToString(command1.Parameters["#dateess_out"].Value);
connection.Close();//close connection
}
return "success";
}
catch (Exception e)
{
return e.ToString();
}
}
My SQL Server stored procedure:
the results
and the query when c# run the code
declare #p4 int
set #p4 = 3
declare #p5 varchar(50)
set #p5 = 'some text'
declare #p6 date
set #p6 = NULL
exec penthhmera_proc #prs_nmb_pen = '274484',
#month_pen = 1,
#year_int = 2021,
#days_out = #p4 output,
#message_out = #p5 output,
#dateess_out = #p6 output
select #p4, #p5, #p6
I think that with that way #p6 is always null.
Finally I want to load all the values from the second recordset to a Gridview or something like a table in order to show it in my webform.
Any idea?
Thanks in advance
ExecuteReader was the answer. thnx Charlieface.
connection.Open();
command1.CommandType = CommandType.StoredProcedure;
SqlDataReader dr = command1.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
//some code
}
dr.NextResult();
while (dr.Read())
{
//some code
}
}
else
{
Console.WriteLine("No data found.");
}

it is showing object cannot cast to DBNull

SqlCommand sd1 = new SqlCommand("select sum(pric) from cart where uid='" +
Convert.ToInt32( Session["uid"]) + "'",con);
// sd1.ExecuteNonQuery();
int var1 = Convert.ToInt32( sd1.ExecuteScalar());
If there is no record then DBNull.Value is returned instead. You need to account for this in your casting. The following will cast to a nullable int so you have a representation if no records were found.
Also use parameters for your queries, not string concatenation.
Code:
int? intResult;
using(SqlCommand sd1 = new SqlCommand("select sum(pric) from cart where uid=#uid", con))
{
sd1.Parameters.Add(new SqlParameter("#uid", SqlDbType.Int){Value = Convert.ToInt32(Session["uid"])});
var result = sd1.ExecuteScalar();
intResult = Syste.DBNull.Value == result
? (int?) null
: (int?) result;
}

how to check in if condition it is string or not

in my search function i need to pass two parameters to SP.Here i kept if condition for that.But am not getting required output. here is my code.any one help me
if (IsValid)
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(myStr);
SqlCommand cmd = new SqlCommand("spRedemItem", con);
cmd.CommandType = CommandType.StoredProcedure;
if(Parameter.Equals(DropDownList2.SelectedValue=="CustomerCode"))
{
cmd.Parameters.AddWithValue("#CustomerCode", txtkey2.Text);
}
else
{
cmd.Parameters.AddWithValue("#CustomerName", txtkey2.Text);
}
SqlDataAdapter sda = new SqlDataAdapter(cmd);
Session["CustomerName"] = dt;
con.Open();
DataSet ds = new DataSet();
sda.Fill(ds);
dt = ds.Tables[0];
Label10.Text = dt.Rows[0]["ItemCode"].ToString();
Label11.Text = dt.Rows[0]["CustomerName"].ToString();
Label12.Text = dt.Rows[0]["PointsNeeded"].ToString();
// Session["CustomerName"] = dt;
View.DataBind();
con.Close();
}
If your sproc has two parameters then you need to pass two parameters every time. Generally you would write your SQL code such that you can just pass NULL to any parameters that you want to ignore, e.g. WHERE (#Column1 IS NULL OR Column1 = #Column1). You then use DBNull.Value for the parameter value if you want to ignore that parameter. You can't use AddWithValue though, because a data type can't be inferred.
E.g.
command.CommandText = #"SELECT *
FROM MyTable
WHERE (#C1 IS NULL OR C1 = #C1)
AND (#C2 IS NULL OR C2 = #C2)";
command.Parameters.Add("#C1", SqlDbType.Int).Value = (someValue == "int"
? Convert.ToInt32(myTextBox.Text)
: (object) DBNull.Value);
command.Parameters.Add("#C2", SqlDbType.VarChar, 50).Value = (someValue == "string"
? myTextBox.Text
: (object) DBNull.Value);

Correct syntax in stored procedure and method using MsSqlProvider.ExecProcedure?

I have problem with ASP.net and stored procedure
My procedure in SQL Server:
ALTER PROCEDURE [dbo].[top1000]
#Published datetime output,
#Title nvarchar(100) output,
#Url nvarchar(1000) output,
#Count INT output
AS
SET #Published = (SELECT TOP 1000 dbo.vst_download_files.dfl_date_public FROM dbo.vst_download_files
ORDER BY dbo.vst_download_files.dfl_download_count DESC )
SET #Title = (SELECT TOP 1000 dbo.vst_download_files.dfl_name FROM dbo.vst_download_files
ORDER BY dbo.vst_download_files.dfl_download_count DESC)
SET #Url = (SELECT TOP 1000 dbo.vst_download_files.dfl_source_url FROM dbo.vst_download_files
ORDER BY dbo.vst_download_files.dfl_download_count DESC)
SET #Count = (SELECT TOP 1000 dbo.vst_download_files.dfl_download_count FROM dbo.vst_download_files
ORDER BY dbo.vst_download_files.dfl_download_count DESC)
And my procedure in website project
public static void Top1000()
{
List<DownloadFile> List = new List<DownloadFile>();
SqlDataReader dbReader;
SqlParameter published = new SqlParameter("#Published", SqlDbType.DateTime2);
published.Direction = ParameterDirection.Output;
SqlParameter title = new SqlParameter("#Title", SqlDbType.NVarChar);
title.Direction = ParameterDirection.Output;
SqlParameter url = new SqlParameter("#Url", SqlDbType.NVarChar);
url.Direction = ParameterDirection.Output;
SqlParameter count = new SqlParameter("#Count", SqlDbType.Int);
count.Direction = ParameterDirection.Output;
SqlParameter[] parm = {published, title, count};
dbReader = MsSqlProvider.ExecProcedure("top1000", parm);
try
{
while (dbReader.Read())
{
DownloadFile df = new DownloadFile();
//df.AddDate = dbReader["dfl_date_public"];
df.Name = dbReader["dlf_name"].ToString();
df.SourceUrl = dbReader["dlf_source_url"].ToString();
df.DownloadCount = Convert.ToInt32(dbReader["dlf_download_count"]);
List.Add(df);
}
XmlDocument top1000Xml = new XmlDocument();
XmlNode XMLNode = top1000Xml.CreateElement("products");
foreach (DownloadFile df in List)
{
XmlNode productNode = top1000Xml.CreateElement("product");
XmlNode publishedNode = top1000Xml.CreateElement("published");
publishedNode.InnerText = "data dodania";
XMLNode.AppendChild(publishedNode);
XmlNode titleNode = top1000Xml.CreateElement("title");
titleNode.InnerText = df.Name;
XMLNode.AppendChild(titleNode);
}
top1000Xml.AppendChild(XMLNode);
top1000Xml.Save("\\pages\\test.xml");
}
catch
{
}
finally
{
dbReader.Close();
}
}
And if I made to MsSqlProvider.ExecProcedure("top1000", parm); I got
String[1]: property Size has invalid size of 0.
Where I should look for solution? Procedure or method?
You need to specify the length property for url and Title
SqlParameter title = new SqlParameter("#Title", SqlDbType.NVarChar);
title.Size=1000
SqlParameter url = new SqlParameter("#Url", SqlDbType.NVarChar);
url.Size=1000
Instead of using an output parameter you can change your query like the one below
ALTER PRocedure [dbo].[top1000]
As
Begin
Select top 1000 dfl_date_public ,dfl_name,dfl_source_url,
dfl_download_count from dbo.vst_download_files
order by dbo.vst_download_files.dfl_download_count DESC
Then use execute reader
SqlCommand command =
new SqlCommand("top1000", connection);
command.CommandType=CommandType.StoredProcedure
SqlDataReader reader = command.ExecuteReader();
// Iterate through reader as u did and add it to the collection
use xelement to frame the XML
foreach (DownloadFile df in List)
{
XElement products=
new XElement("Products",
new XElement("product",
new XElement("published", "data dodania"),
new XElement("title", df.Name)
);
}

insert a database value to a string array - not working

Cheers,
Im trying to insert a database value to my string array.
for some reason, it says :
"Object reference not set to an instance of an object."
This is my code :
if (IsPostBack)
{
if (RadioWords.Checked == true)
{
con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Daniel;Integrated Security=True");
con.Open();
string SqlCount = "SELECT COUNT(*) FROM WordGame";
SqlCommand command = new SqlCommand(SqlCount, con);
//Sets an array of the size of the database.
int count = (Int32)command.ExecuteScalar();
arrOfWords = new string[count];
//Initialize the words in the array.
for (int i = 0; i < arrOfWords.Length; i++)
{
int GetRandomNumber = rnd.Next(1, arrOfWords.Length);
string Sqlinsert = "SELECT Word FROM WordGame WHERE ID='"+GetRandomNumber+"'";
SqlCommand commandToRandom = new SqlCommand(Sqlinsert, con);
arrOfWords[i] = commandToRandom.ExecuteScalar().ToString();
}
}
and its refering to this line :
int GetRandomNumber = rnd.Next(1, arrOfWords.Length);
Thanks for the helpers!
rnd is null , add a line
rnd = new Random();
at the start of your event
rnd = new Random();
Instantiate rnd as above. You're using a null object that causes the exception in your question to be thrown.

Resources