it is showing object cannot cast to DBNull - asp.net

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;
}

Related

error:Must declare the scalar variable "#ID" asp.net & sql server2014

asp.net & sql server 2014 : why this error appearMust declare the scalar variable"#ID" I looked on goggle and I think it has something to do with insert parameters for ID. Then again I read there could be a typo error.
As I am not going to insert ID column manually I think this is why I am having problem(s) and I don't know how to solve this problem. i cant find out what is missing or wrong could you help please
string query = "insert into LegRent(ID, Day, Date, Name, Nationality, relegon, NatID, Name2, Nationality2, relegon2, NatID2, Type, Building, Flat, UseFor, Duration, StartFrom, EndIn, RentValue, OnlyAr, YearPercent, InsuranceValue, OnlyArInsur, Addres2, Addres) values (#ID, #Day, #Date, #Name, #Nationality, #relegon, #NatID, #Name2, #Nationality2, #relegon2, #NatID2, #Type, #Building, #Flat, #UseFor, #Duration, #StartFrom, #EndIn, #RentValue, #OnlyAr, #YearPercent, #InsuranceValue, #OnlyArInsur, #Addres2, #Addres)";
try
{
string query2 = "Select ##Identity";
int ID;
string connect = "Provider=SQLOLEDB;Data Source=.;Initial Catalog=Construction;Integrated Security=SSPI;";
using (OleDbConnection conn2 = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn2))
{
cmd.Parameters.AddWithValue("#ID", idtxt.Text);
cmd.Parameters.AddWithValue("#Day", daytxt.Text);
cmd.Parameters.AddWithValue("#Date", datetxt.Text);
cmd.Parameters.AddWithValue("#Name", namedd.Text);
cmd.Parameters.AddWithValue("#Nationality", ddNati.Text);
cmd.Parameters.AddWithValue("#relegon", ddRelgon.Text);
cmd.Parameters.AddWithValue("#NatID", NatIDtxt.Text);
cmd.Parameters.AddWithValue("#Name2", namedd2.Text);
cmd.Parameters.AddWithValue("#Nationality2", ddNati2.Text);
cmd.Parameters.AddWithValue("#relegon2", ddRelgon2.Text);
cmd.Parameters.AddWithValue("#NatID2", NatIDtxt2.Text);
cmd.Parameters.AddWithValue("#Type", typrdd.Text);
cmd.Parameters.AddWithValue("#Building", buileddd.Text);
cmd.Parameters.AddWithValue("#Flat", flatdd.Text);
cmd.Parameters.AddWithValue("#UseFor", usetxt.Text);
cmd.Parameters.AddWithValue("#Duration", durationtxt.Text);
cmd.Parameters.AddWithValue("#StartFrom", starttxt.Text);
cmd.Parameters.AddWithValue("#EndIn", endtxt.Text);
cmd.Parameters.AddWithValue("#RentValue", vluetxt.Text);
cmd.Parameters.AddWithValue("#OnlyAr", onlytxt.Text);
cmd.Parameters.AddWithValue("#InsuranceValue", insurtxt.Text);
cmd.Parameters.AddWithValue("#OnlyArInsur", insuronlytxt.Text);
cmd.Parameters.AddWithValue("#YearPercent", percenttxt.Text);
cmd.Parameters.AddWithValue("#Addres2", adresstxt2.Text);
cmd.Parameters.AddWithValue("#Addres", adresstxt.Text);
conn2.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = query2;
ID = (int)cmd.ExecuteScalar();
lbl_msg.Text = "تـــم الحفظ";
int rentMonths = 0;
bool isInt = int.TryParse(durationtxt.Text, out rentMonths);
if (isInt)
{
for (int index = 0; index < rentMonths; index++)
{
OleDbCommand insertRentMonths = new OleDbCommand("INSERT INTO [dbo].[AccRentReceipt] ([ReceiptID] ,[ContractID] ,[Name]) VALUES (#ReceiptID ,#ContractID ,#Name)", conn2);
cmd.Parameters.AddWithValue("#ReceiptID", index + 1);
cmd.Parameters.AddWithValue("#ContractID", ID);
cmd.Parameters.AddWithValue("#Name", namedd.Text);
}
}
}
}
}
catch (Exception ex)
{
lbl_msg.Text = "خطــــأ " + ex.Message;
}

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);

How can I store sql table row count in a string variable?

I am trying to store the result of query string
q = "select count(*) from test" (asp.net c#)
in a string variable so that I can display the count on a label on button click.
int RecordCount;
RecordCount = Convert.ToInt32(cmd.ExecuteScalar());
string myString = RecordCount.ToString();
The value of ExecuteScalar can be null, make sure you check for null
int RecordCount = 0;
object retVal = cmd.ExecuteScalar();
if(retVal != null)
RecordCount = Convert.ToInt32(cmd.ExecuteScalar());

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.

ExecuteScalar throws NullReferenceException

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;

Resources