NullReferenceException: Object reference not set to an instance of an object #2 - c#

Error shown on the website. Im using asp net visual C# webform, access data source (MS access) When I click on Add to Cart button on productdetails.aspx
Line 41: int intOrderNo = (int)Session["sOrderNo"];
Line 42: string strUnitPrice = (string)Session["sUnitPrice"];
Line 43: decimal decUnitPrice = decimal.Parse(strUnitPrice);
For myOrder table in Ms Access
There is oOrderNo, oDate, oUserName, oPaymentMode, oStatus,
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
// test to remind customer to login first
if ((string)Session["sFlag"]!="T")
{
Type csType = this.GetType();
ClientScript.RegisterStartupScript(csType, "Error", scriptErrorLogin);
}
// Connect to database
OleDbConnection mDB = new OleDbConnection();
mDB.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0;Data source=" + Server.MapPath("~/App_Data/webBase.accdb");
mDB.Open();
OleDbCommand cmd;
DetailsViewRow row0 = DetailsView1.Rows[0];
string strProductID = row0.Cells[1].Text;
mDB.Close();
// save as session variables
Session["sProductID"] = strProductID;
DetailsViewRow row4 = DetailsView1.Rows[4];
Session["sUnitPrice"] = row4.Cells[1].Text;
int intOrderNo = (int)Session["sOrderNo"];
string strUnitPrice = (string)Session["sUnitPrice"];
decimal decUnitPrice = decimal.Parse(strUnitPrice);
string strSQL = "INSERT INTO orderItems(uOrderNo, uProductID, uUnitPrice)" + "VALUES(#eOrderNo, #eProductID, #eUnitPrice)";
cmd = new OleDbCommand(strSQL, mDB);
cmd.Parameters.AddWithValue("#eOrderNo", intOrderNo);
cmd.Parameters.AddWithValue("#eProductID", strProductID);
cmd.Parameters.AddWithValue("#eUnitPrice", decUnitPrice);
mDB.Open();
cmd.ExecuteNonQuery();
mDB.Close();
Response.Redirect("ShoppingCart.aspx");

Try this
Line 41: int intOrderNo = Session["sOrderNo"] == DBNull.Value ? 0 : (int)Session["sOrderNo"];
Line 42: string strUnitPrice = Session["sUnitPrice"] == DBNull.Value ? string.Empty : (string)Session["sUnitPrice"];
null Vs DBNull.Value

Try below code :
Line 41: int intOrderNo = Session["sOrderNo"] == null ? 0 : (int)Session["sOrderNo"];
Line 42: string strUnitPrice = Session["sUnitPrice"] == null ? string.Empty : (string)Session["sUnitPrice"];
Line 43: decimal decUnitPrice = string.IsNullOrWhiteSpace(strUnitPrice) ? 0 : decimal.Parse(strUnitPrice);

Just check that if Session variable is Null-
if( Session["sOrderNo"] != null && all the session variables )
{
//Now check your condition here
}
else {
//Perform any operation
}

Related

If there is no row in database sum command return an error

An error is thrown when there is no data in data base while converting a string value into int.
try {
SqlCommand cmdc = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=1 AND Crdt_typ_id=1", con);
string companya_credit_amount = null, comapnyb_credit_amount = null;
con.Open();
SqlDataReader drc = cmdc.ExecuteReader();
if (drc.HasRows)
{
while (drc.Read())
{
companya_credit_amount = drc[0].ToString();
}
drc.Close();
con.Close();
}
SqlCommand cmdcp = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=2 AND Crdt_typ_id=1", con);
con.Open();
SqlDataReader drcp = cmdcp.ExecuteReader();
if (drcp.HasRows)
{
while (drcp.Read())
{
companyb_credit_amount = drcp[0].ToString();
}
drcp.Close();
con.Close();
}
if (!Page.IsPostBack)
{
int companyA = 0,companyB=0;
if (companya_credit_amount != "") { companyA = Convert.ToInt32(credit_amount.ToString()); }
if (companyb_credit_amount != ""){ companyB = Convert.ToInt32(companyb_credit_amount); }
int total = (companyA+companyB);
count_total_lbl.Text = "Rs." + " " + total.ToString();
count_comapnya_lbl.Text = "Rs." + " " + companya_credit_amount.ToString();
count_companyb_lbl.Text ="Rs."+" "+ companyb_credit_amount.ToString();
}
}
catch(Exception ex) { Label2.Text = ex.ToString(); }
If there is value its working fine.but when there is no value in data base there is an error msg.
System.FormatException: Input string was not in a correct format.
Use IsDBNull to check for null values
Create and destroy all your type instances that implement IDisposable in using blocks. This ensures that connections are always released and resources are cleaned up.
Do not use connections across a class. Create them when needed and then dispose of them. Sql Server will handle connection pooling.
Get the native types directly, not the string equivalent! See changes to GetInt32 instead of ToString on the data reader.
You should refactor this to use SqlParameter's and make the retrieval statement generic OR get both SUM values in 1 sql call.
There is an if (!Page.IsPostBack) statement, if none of this code does anything if it is a postback then check at the top of the page and do not execute the sql statements if it is a postback. Otherwise the code is making (possibly) expensive sql calls for no reason.
try
{
int companyA = 0,companyB=0;
using(var con = new SqlConnection("connectionStringHere"))
{
con.Open();
using(SqlCommand cmdc = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=1 AND Crdt_typ_id=1", con))
using(SqlDataReader drc = cmdc.ExecuteReader())
{
if (drc.Read() && !drc.IsDBNull(0))
companyA = drc.GetInt32(0);
}
using(SqlCommand cmdcp = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=2 AND Crdt_typ_id=1", con))
using(SqlDataReader drcp = cmdcp.ExecuteReader())
{
if (drcp.Read() && !drcp.IsDBNull(0))
companyB = drcp.GetIn32(0);
}
}
// if you are not going to do anything with these values if its not a post back move the check to the top of the method
// and then do not execute anything if it is a postback
// ie: // if (Page.IsPostBack) return;
if (!Page.IsPostBack)
{
int total = (companyA+companyB);
count_total_lbl.Text = "Rs." + " " + total.ToString();
count_comapnya_lbl.Text = "Rs." + " " + companyA.ToString();
count_companyb_lbl.Text ="Rs."+" "+ companyB.ToString();
}
}
catch(Exception ex) { Label2.Text = ex.ToString(); }
Try to replace this
SELECT SUM(Credited_amount)
WITH
SELECT ISNULL(SUM(Credited_amount),0)
Also find one confusing code while converting Credited amount values
if (companya_credit_amount != "") { companyA = Convert.ToInt32(credit_amount.ToString()); }
---------^^^^^
if (companyb_credit_amount != ""){ companyB = Convert.ToInt32(companyb_credit_amount); }
I don't know about your business requirement but What i think Instead of using credit_amount value companya_credit_amount should be use to show value for companyA variable right?
You should do 2 things:
string companya_credit_amount = "", comapnyb_credit_amount = "";
Before assigning the value to these string variable you should check for db null as following:
while (drc.Read())
{
companya_credit_amount = (drc[0] != DbNull.Value) ? drc[0].ToString() : "" ;
}
Similarely
while (drcp.Read())
{
companyb_credit_amount = (drcp[0] != DbNull.Value) ? drcp[0].ToString() : "";
}
Try it.
You need to initialize credit_amount to empty and check if db value is null as shown below:
try {
companya_credit_amount = string.Empty;
companyb_credit_amount = string.Empty;
SqlCommand cmdc = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=1 AND Crdt_typ_id=1", con);
string companya_credit_amount = null, comapnyb_credit_amount = null;
con.Open();
SqlDataReader drc = cmd
c.ExecuteReader();
if (drc.HasRows)
{
while (drc.Read())
{
companya_credit_amount = drcp.IsDBNull(0)?string.Empty:Convert.ToString(drcp[0]);
}
drc.Close();
con.Close();
}
SqlCommand cmdcp = new SqlCommand("SELECT SUM(Credited_amount) FROM IMS_Credit_Dir WHERE Credit_comp_id=2 AND Crdt_typ_id=1", con);
con.Open();
SqlDataReader drcp = cmdcp.ExecuteReader();
if (drcp.HasRows)
{
while (drcp.Read())
{
companyb_credit_amount = drcp.IsDBNull(0)?string.Empty:Convert.ToString(drcp[0]);
}
drcp.Close();
con.Close();
}
if (!Page.IsPostBack)
{
int companyA = 0,companyB=0;
if (companya_credit_amount != "") { companyA = Convert.ToInt32(credit_amount.ToString()); }
if (companyb_credit_amount != ""){ companyB = Convert.ToInt32(companyb_credit_amount); }
int total = (companyA+companyB);
count_total_lbl.Text = "Rs." + " " + total.ToString();
count_comapnya_lbl.Text = "Rs." + " " + companya_credit_amount.ToString();
count_companyb_lbl.Text ="Rs."+" "+ companyb_credit_amount.ToString();
}
}
catch(Exception ex) { Label2.Text = ex.ToString(); }

Conversion failed from varchar to int, ado.net

I'm working with sql databases via ado.net in c# and I'm trying to pass the following update command:
cmd.CommandText = #"UPDATE VehicleContract SET regNr='#reg', assoc_id='#assort', percentage='#perc', vehicleType='#type', trailerNr='#trailer' WHERE contractId='#id'";
cmd.Parameters.AddWithValue("#id", id);
id is in int. I read it as an int. I even do a int.Parse(txtbox.text) and everything is fine. But then when I insert all the values in the boxes, press submit. I get the conversion error saying that it can't convert '#id' varchar to int... it makes no sense
Is there any specific thing I'm not doing right? Need any more details?
The whole code:
if (tbid.Text == "" || tbper.Text == "" || tbas.Text == "" || tbvt.Text == "")
{
MessageBox.Show("All fields must be filled ");
return;
}
if (tbreg.Text == "" && tbtn.Text == "")
{
MessageBox.Show("Fill at least one from: Registration nr or trailer nr");
return;
}
int id = 0;
string reg = "";
int assort = 0;
int perc = 0;
string type = "";
int trailer = 0;
try
{
id = int.Parse(tbid.Text);
Console.Write(id);
if (tbreg.Text != "")
{
reg = tbreg.Text;
}
assort = int.Parse(tbas.Text);
perc = int.Parse(tbper.Text);
type = tbvt.Text;
if (tbtn.Text != "")
{
trailer = int.Parse(tbtn.Text);
}
}
catch (Exception ee)
{
MessageBox.Show("id, assoc, perc and trailer nr must be integers ");
return;
}
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
con.ConnectionString = "Data Source=.;initial Catalog=Lab5;integrated security=true";
con.Open();
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"UPDATE VehicleContract SET regNr='#reg', assoc_id='#assort', percentage='#perc', vehicleType='#type', trailerNr='#trailer' WHERE contractId='#id'";
cmd.Parameters.AddWithValue("#id", id);
if (reg == "")
{
cmd.Parameters.AddWithValue("#reg", DBNull.Value);
}
else
{
cmd.Parameters.AddWithValue("#reg", reg);
}
cmd.Parameters.AddWithValue("#assort", assort);
cmd.Parameters.AddWithValue("#perc", perc);
cmd.Parameters.AddWithValue("#type", type);
if (trailer == 0)
{
cmd.Parameters.AddWithValue("#trailer", DBNull.Value);
}
else
{
cmd.Parameters.AddWithValue("#trailer", trailer);
}
cmd.Connection = con;
SqlDataReader sdr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(sdr);
childgrid.DataSource = dt;
sdr.Close();
con.Close();
When you use WHERE contractId='#id' in a query you are comparing the int contractId column with the string '#id' value.
You need to use WHERE contractId=#id.
So remove single quotes around #id and other parameters.

Error on C# when trying to fetch multiple data from database

I have this code in C#:
private void sqlConnLabel()
{
NoIDPenghuni = new SqlParameter();
SqlConnection con = new SqlConnection(strCon);
com2 = new SqlCommand();
com2.Connection = con;
con.Open();
com2.CommandType = CommandType.StoredProcedure;
com2.CommandText = "label";
NoIDPenghuni.SqlDbType = SqlDbType.VarChar;
NoIDPenghuni.Size = 50;
NoIDPenghuni.ParameterName = "#NoIDPenghuni";
NoIDPenghuni.Value = NoIDPenghuniC;
NoIDPenghuni.Direction = ParameterDirection.Input;
com2.Parameters.Add(NoIDPenghuni);
string NamaPenghuni;
string JKPenghuni;
string NoTelpPenghuni;
string AlamatPenghuni;
string NoKamar;
NamaPenghuni = Convert.ToString(com2.ExecuteScalar());
JKPenghuni = Convert.ToString(com2.ExecuteScalar());
NoTelpPenghuni = Convert.ToString(com2.ExecuteScalar());
AlamatPenghuni = Convert.ToString(com2.ExecuteScalar());
NoKamar = Convert.ToString(com2.ExecuteScalar());
SqlDataReader reader = com2.ExecuteReader();
while (reader.Read())
{
NamaPenghuni = reader["NamaPenghuni"] == DBNull.Value ? null : (string)reader["NamaPenghuni"];
JKPenghuni = reader["JKPenghuni"] == DBNull.Value ? null : (string)reader["JKPenghuni"];
NoTelpPenghuni = reader["NoTelpPenghuni"] == DBNull.Value ? null : (string)reader["NoTelpPenghuni"];
AlamatPenghuni = reader["AlamatPenghuni"] == DBNull.Value ? null : (string)reader["AlamatPenghuni"];
NoKamar = reader["NoKamar"] == DBNull.Value ? null : (string)reader["NoKamar"];
}
label9.Text = NoIDPenghuniC;
label8.Text = NamaPenghuni;
if (JKPenghuni == "P")
label7.Text = "Male";
else
label7.Text = "Female";
label6.Text = NoTelpPenghuni;
label18.Text = AlamatPenghuni;
label5.Text = NoKamar;
con.Close();
}
When I try to run it keeps telling me
IndexOutOfRangeException was unhandled.
I think the data won't be fetched into my C#. It only takes the 'NamaPenghuni'
For example: if I take the data with NoIDPenghuni='110801101, the NamaPenghuni should be Priska Hapsari, the JKPenghuni should be W, the NoTelpPenghuni should be 08567711332, and the AlamatPenghuni should be Jl. Mega Cinere No. 29, Cinere.
But on my locals section I can see that all those string variables values are Priska Hapsari.
What did I do wrong?
You call for 5 times the ExecuteScalar before the ExecuteReader.
ExecuteScalar returns the first column of the first row (just one result).
Calling it 5 times results in the same value for the all 5 variables
The IndexOutOfRange exception could be caused by the following ExecuteReader that expects to find 5 columns in the returned values, but we can't see if the StoredProcedure returns effectively 5 values per row

Assigning SQL value retrieved of dept to Session["UserAuthentication"]

I'm retrieving the value of dept with following SQL query wirrten in C# from the table ts_dept - how would I assign it to Session["UserAuthentication"] when (CurrentName != null)?
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
string username = Login_Box.UserName;
string pwd = Login_Box.Password;
string strConn;
strConn = WebConfigurationManager.ConnectionStrings["team13ConnectionString"].ConnectionString;
SqlConnection Conn = new SqlConnection(strConn);
Conn.Open();
string sqlUserName;
sqlUserName = "SELECT dept FROM ts_dept WHERE id=#username AND pass=#pwd";
SqlCommand com = new SqlCommand(sqlUserName, Conn);
com.Parameters.Add("#username", username);
com.Parameters.Add("#pwd", pwd);
string CurrentName;
CurrentName = (string)com.ExecuteScalar();
if (CurrentName != null)
{
Session["UserAuthentication"] = username;
Session.Timeout = 1;
Response.Redirect("Default.aspx");
}
else
{
Session["UserAuthentication"] = "";
}
}
Just going from memory here (not at my C# machine), but try this:
object CurrentName = com.ExecuteScalar();
if (CurrentName != null && CurrentName != System.DBNull.Value) {
{
Session["UserAuthentication"] = (string)CurrentName;
Session.Timeout = 1;
Response.Redirect("Default.aspx");
}
else
{
Session["UserAuthentication"] = "";
}
}
If I recall correctly, CurrentName will be null if the query returns no results, or System.DBNull.Value if the query returns a result but ts_dept.dept is null.
Also take heed of the comment about using Session for authentication - if you're in a load-balanced cluster it just plain won't work. Start switching this to Forms authentication.

Invalid attempt to access a field before calling Read()

I'm getting the error:
Invalid attempt to access a field before calling Read()
at: string result = Reader.GetString(0);
I'm not entirely sure what to do or whats wrong though
internal int GetCharGuidByName(string charactername, MySqlConnection connection)
{
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "SELECT guid FROM characters WHERE name=\""+charactername+"\";";
// Initialize MySQL Reader
Reader = command.ExecuteReader();
Reader.Read();
string result = Reader.GetString(0);
// If the character doesn't exist or isn't entered, return 0
int charguid = 0;
if (result != String.Empty)
{
charguid = Convert.ToInt32(result);
}
return charguid;
}
Change the code to:
Reader = command.ExecuteReader();
int charguid = 0;
if(Reader.Read())
{
if(Reader[0] != DBNull.Value)
{
if(int.TryParse(Reader[0].ToString(), out charguid))
{
//value read and is an integer!
}
}
}
return charguid;
You should use ExecuteScalar instead of ExecuteReader
ExecuteSaclar returns the first column of the first row in the result
set, or a null reference
ExecuteReader will return as resultset which you have to then iterate
to read
So looking at your code you just want the first column of the result set
internal int GetCharGuidByName(string charactername, MySqlConnection connection)
{
int charguid = 0;
using(MySqlCommand command = connection.CreateCommand())
{
command.CommandText = "SELECT guid FROM characters WHERE name=\""+charactername+"\";";
object obj = command.ExecuteScalar();
if (obj != null && obj != DBNull.Value)
{
charguid = Convert.ToInt32(obj);
}
}
return charguid;
}
openConnection()
sql = "SELECT last, first, emp_type, active FROM employee INNER JOIN account ON employee.emp_id = account.emp_id WHERE employee.emp_id = '" & AtxtEmpID.Text & "'"
command = New MySqlCommand(sql, mySqlConnection)
reader = command.ExecuteReader
reader.Read()
AtxtEmpName.Text = reader.Item(0) & ", " & reader.Item(1)
closeConn()
have the save problem

Categories

Resources