Null Reference Exception when Clicking a button in ASP.NET Webforms - c#
I have created a web application for online testing.
The website is running perfectly fine on my local machine but giving an error on remote server.
protected void Page_Load(object sender, EventArgs e)
{
arrSessionALL_questions = Session["arrALL_questions"] as int[];
arrSessionQuestion_ID = Session["arrayOfQuestionID"] as int[];
arrSessionCorrectAns = Session["arrayOfCorrectAns"] as string[];
arrSessionCorrectAnsMarks = Session["arrayOfCorrectAnsMarks"] as int[];
arrSessionAns_ID = Session["arrayOfAnsID"] as string[];
arrSessionAttempted_ID = Session["arrayOfAttemptedID"] as int[];
arrSessionMarkQuestion_ID = Session["arrMarkQuestion_ID"] as int[];
arrSessionLeft_ID = Session["arrayOfLeftID"] as int[];
arrSessionTotalMarks = Session["arrTotalMarks"] as int[];
}
protected void ButtonNext_Click(object sender, EventArgs e)
{
PanelTimer.Visible = true;
PanelQuestNum.Visible = false;
try
{
if (arrSessionQuestion_ID[Convert.ToInt32(Session["QuestionCounter"])] != 0)
{
if (Convert.ToInt32(Session["QuestionCounter"]) < arrSessionALL_questions.Length)
{
//Session["QuestionCounter"] = Convert.ToInt32(Session["QuestionCounter"]) + 1;
LabelStudentName.Text = arrSessionQuestion_ID[Convert.ToInt32(Session["QuestionCounter"])].ToString();
correctAns = arrSessionCorrectAns[Convert.ToInt32(Session["QuestionCounter"])].ToString();
correctMarks = Convert.ToInt32(arrSessionCorrectAnsMarks[Convert.ToInt32(Session["QuestionCounter"])]);
PanelQ.Visible = true;
ButtonSTART.Visible = false;
ButtonMark.Visible = true;
PanelTimer.Visible = true;
PanelQuestNum.Visible = false;
if (RadioButtonListAns.SelectedIndex >= 0)
{
arrAns_ID[Convert.ToInt32(Session["QuestionCounter"])] = RadioButtonListAns.SelectedItem.ToString();
Session["arrayOfAnsID"] = arrAns_ID;
arrSessionAns_ID = Session["arrayOfAnsID"] as string[];
if (arrSessionAns_ID[Convert.ToInt32(Session["QuestionCounter"])] == correctAns)
{
studentMarks = correctMarks;
attempt_correct_wrong = "correct";
}
else
{
studentMarks = 0;
attempt_correct_wrong = "wrong";
}
con.Open();
SqlDataAdapter adp = new SqlDataAdapter("select * from Student_Analysis where((date='" + date + "' AND username='" + username + "') AND (PaperName='" + papername + "' AND QuestionNumber='" + arrSessionQuestion_ID[Convert.ToInt32(Session["QuestionCounter"])] + "'))", con);
DataSet ds = new DataSet();
adp.Fill(ds, "Student_Analysis");
int count = ds.Tables[0].Rows.Count;
if (count > 0)
{
con.Close();
con1.Open();
SqlCommand cmd = new SqlCommand("UPDATE Student_Analysis set studentAns='" + arrSessionAns_ID[Convert.ToInt32(Session["QuestionCounter"])] + "',studentMarks='" + studentMarks + "',attemp_correct_wrong='" + attempt_correct_wrong + "' where((date='" + date + "' AND username='" + username + "') AND (PaperName='" + papername + "' AND QuestionNumber='" + arrSessionQuestion_ID[Convert.ToInt32(Session["QuestionCounter"])] + "'))", con1);
cmd.ExecuteNonQuery();
con1.Close();
}
else
{
con.Close();
con1.Open();
SqlCommand cmd = new SqlCommand("insert into Student_Analysis values('" + date + "','" + studentId.ToString() + "','" + studentName + "','" + username.ToString() + "','" + papername + "','" + Convert.ToInt32(LabelStudentName.Text) + "','" + arrSessionAns_ID[Convert.ToInt32(Session["QuestionCounter"])] + "','" + correctAns + "','" + studentMarks + "','" + correctMarks + "','" + attempt_correct_wrong + "')", con1);
cmd.ExecuteNonQuery();
con1.Close();
}
}
else
{
arrAns_ID[Convert.ToInt32(Session["QuestionCounter"])] = "NULL";
Session["arrayOfAnsID"] = arrAns_ID;
arrSessionAns_ID = Session["arrayOfAnsID"] as string[];
studentMarks = 0;
attempt_correct_wrong = "Not attempted";
con.Open();
SqlDataAdapter adp = new SqlDataAdapter("select * from Student_Analysis where((date='" + date + "' AND username='" + username + "') AND (PaperName='" + papername + "' AND QuestionNumber='" + arrSessionQuestion_ID[Convert.ToInt32(Session["QuestionCounter"])] + "'))", con);
DataSet ds = new DataSet();
adp.Fill(ds, "Student_Analysis");
int count = ds.Tables[0].Rows.Count;
if (count > 0)
{
con.Close();
con1.Open();
SqlCommand cmd = new SqlCommand("UPDATE Student_Analysis set studentAns='" + "NULL" + "',studentMarks='" + studentMarks + "',attemp_correct_wrong='" + attempt_correct_wrong + "' where((date='" + date + "' AND username='" + username + "') AND (PaperName='" + papername + "' AND QuestionNumber='" + arrSessionQuestion_ID[Convert.ToInt32(Session["QuestionCounter"])] + "'))", con1);
cmd.ExecuteNonQuery();
con1.Close();
}
else
{
con.Close();
con1.Open();
SqlCommand cmd = new SqlCommand("insert into Student_Analysis values('" + date + "','" + studentId.ToString() + "','" + studentName + "','" + username.ToString() + "','" + papername + "','" + Convert.ToInt32(LabelStudentName.Text) + "','" + "NULL" + "','" + correctAns + "','" + studentMarks + "','" + correctMarks + "','" + attempt_correct_wrong + "')", con1);
cmd.ExecuteNonQuery();
con1.Close();
}
}
if (Convert.ToInt32(Session["QuestionCounter"]) < arrSessionALL_questions.Length - 1)
{
Session["QuestionCounter"] = Convert.ToInt32(Session["QuestionCounter"]) + 1;
loadQuestion();
ButtonMark.Visible = true;
//Checking if question has been marked
con.Open();
SqlDataAdapter adp = new SqlDataAdapter("select * from StudentMarkedQuestions where((date='" + date + "' AND username='" + username + "') AND (PaperName='" + papername + "' AND markedQuestionNumber='" + arrSessionQuestion_ID[Convert.ToInt32(Session["QuestionCounter"])] + "'))", con);
DataSet ds = new DataSet();
adp.Fill(ds, "Student_Analysis");
int count = ds.Tables[0].Rows.Count;
if (count > 0)
{
ButtonMark.Visible = false;
ButtonUnMark.Visible = true;
}
else
{
ButtonMark.Visible = true;
ButtonUnMark.Visible = false;
}
//Checking if question has been marked
}
else
{
LabelStudentName.Text = "End of questions!!";
PanelQ.Visible = true;
ButtonSTART.Visible = false;
ButtonFinish.Visible = true;
ButtonNext.Visible = true;
ButtonPrevious.Visible = true;
}
}
else
{
LabelStudentName.Text = "End of questions!!";
PanelQ.Visible = true;
ButtonSTART.Visible = false;
ButtonFinish.Visible = true;
ButtonMark.Visible = false;
ButtonPrevious.Visible = false;
ButtonNext.Visible = false;
ButtonUnMark.Visible = false;
}
}
} //try ends
catch(Exception ex)
{
Response.Write(ex.Message);
}
}
public void loadQuestion()
{
if (arrSessionQuestion_ID[Convert.ToInt32(Session["QuestionCounter"])] != 0)
{
con1.Open();
SqlDataAdapter adp1 = new SqlDataAdapter("select * from QuestionInsert where(QuestionNum='" + arrSessionQuestion_ID[Convert.ToInt32(Session["QuestionCounter"])] + "')", con1);
DataSet ds1 = new DataSet();
adp1.Fill(ds1);
LabelQuestion.Text = (Convert.ToInt32(Session["QuestionCounter"]) + 1) + ". " + ds1.Tables[0].Rows[0][7].ToString();
con1.Close();
RadioButtonListAns.Items.Clear();
con2.Open();
string strQuery = "select * from QuestionInsert where(QuestionNum='" + arrSessionQuestion_ID[Convert.ToInt32(Session["QuestionCounter"])] + "')";
SqlDataAdapter da = new SqlDataAdapter(strQuery, con2);
DataTable dt = new DataTable();
da.Fill(dt);
con2.Close();
RadioButtonListAns.Items.Insert(0, new ListItem(dt.Rows[0]["Option1"].ToString(), dt.Rows[0]["Option1"].ToString()));
RadioButtonListAns.Items.Insert(1, new ListItem(dt.Rows[0]["Option2"].ToString(), dt.Rows[0]["Option2"].ToString()));
RadioButtonListAns.Items.Insert(2, new ListItem(dt.Rows[0]["Option3"].ToString(), dt.Rows[0]["Option3"].ToString()));
RadioButtonListAns.Items.Insert(3, new ListItem(dt.Rows[0]["Option4"].ToString(), dt.Rows[0]["Option4"].ToString()));
RadioButtonListAns.Items.Insert(4, new ListItem(dt.Rows[0]["Option5"].ToString(), dt.Rows[0]["Option5"].ToString()));
//Selects radiobutton if answer found in database
con3.Open();
SqlDataAdapter adp = new SqlDataAdapter("select * from Student_Analysis where((date='" + date + "' AND username='" + username + "') AND (PaperName='" + papername + "' AND QuestionNumber='" + arrSessionQuestion_ID[Convert.ToInt32(Session["QuestionCounter"])] + "'))", con3);
DataSet ds = new DataSet();
adp.Fill(ds, "Student_Analysis");
int count = ds.Tables[0].Rows.Count;
if (count > 0)
{
con3.Close();
string ans = ds.Tables[0].Rows[0][6].ToString();
if (RadioButtonListAns.Items.FindByText(ans) != null)
{
RadioButtonListAns.Items.FindByText(ans).Selected = true;
}
}
con3.Close();
//Selects radiobutton if answer found in database
}
}
This is the code that I have applied, I have given the code from Page Load and ButtonNext_Click() event.
While starting the test, it loads two questions but then if you will click on next button again, it is giving me this error:
[NullReferenceException: Object reference not set to an instance of an object.]
StudentTestingPage.ButtonNext_Click(Object sender, EventArgs e) +2018
System.EventHandler.Invoke(Object sender, EventArgs e) +0
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9553178
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +103
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724
I tried everything that I know and searched about everything on internet but still unable to fix it.
I have checked all the variables and arrays that can be set to null, the code is running fine on local machine.
I have used SQL Server as database.
The clue is in the stack trace. You are calling a method or getting/setting a property on something that is null in the handler for ButtonNext.
Look at your ButtonNext_Click() method and try to see what objects might be null.
If you can't replicate locally, then consider building a DEBUG build and deploying that. That should give you the actual line number throwing the exception in the stack trace.
However
This code has many serious issues. If you work on improving the overall quality of the code, simple things like NullReferenceException become easier to locate and resolve.
Method length You need to cut your frankly MASSIVE ButtonNext_Click() method into many, small (maybe even less than 10 lines) descriptively-named methods. If you have ReSharper learn how to use it. If you don't, buy it and learn how to use it. However even Visual Studio has "Extract Method" these days - USE IT. In particular the contents of if/else blocks might be good candidates.
SQL Injection You are being very naughty - concatenating SQL strings is a BAD IDEA. Instead, parameterise your SQL strings. Better still, use Entity Framework (comes free in the .NET framework) or something like Dapper.
Don't use "NULL". Use null and note the important difference.
One last thing - you shouldn't see the Yellow Screen of Death, really. You should always turn it off in production in your web.config:
<customErrors mode="RemoteOnly" ... />
Related
else condition not working when reader hasrows is false
Can somebody tell me why the else condition is not working in the code below. The link button in asp.net web application has following code in code behind: a parameterized SqlCommand fetch a row from a SQL Server database, the SqlDataReader rdr1.HasRows in if condition is working fine but else condition did not work. Code updated protected void LinkButton1_Click(object sender, EventArgs e) { string comid = DropDownList4.SelectedValue.ToString(); using (SqlConnection con = new SqlConnection(cs)) { SqlCommand cmd = new SqlCommand("Select * from Commercials Where id =" + comid, con); con.Open(); SqlDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { string dur = rdr["duration"].ToString(); Char delimiter = '/'; string[] dd = DateTime.Parse(rdr["rodate"].ToString()).ToString("dd/MM/yyyy").Split(delimiter); if (DropDownList3.SelectedValue.ToString().Contains("BOL NEWS") == true && DropDownList1.SelectedValue.ToString().Contains("After Headlines") == true) { SqlConnection con0 = new SqlConnection(cs); string sql01 = "Select * from CTS Where air_time=(Select max(air_time) from CTS where air_date=#airdate and air_time Like #airtime and channel=#channel and Slot=#slot) and air_date=#airdate1"; con0.Open(); SqlCommand cmd1 = new SqlCommand(sql01, con0); cmd1.Parameters.AddWithValue("#airdate", TextBox1.Text); cmd1.Parameters.AddWithValue("#channel", DropDownList3.SelectedValue.ToString()); cmd1.Parameters.AddWithValue("#airtime", DropDownList2.SelectedValue.ToString().Substring(0, 2) + "%"); cmd1.Parameters.AddWithValue("#slot", DropDownList1.SelectedValue.ToString().Remove(0, 3)); cmd1.Parameters.AddWithValue("#airdate1", TextBox1.Text); SqlDataReader rdr1 = cmd1.ExecuteReader(); while (rdr1.Read()) { string startTime0 = rdr1["air_time"].ToString(); string addsec = rdr1["duration"].ToString(); if (rdr1.HasRows) { DateTime startTime1 = DateTime.ParseExact(startTime0, "HH:mm:ss", null); string startHeadlines_ = startTime1.AddSeconds(int.Parse(addsec)).ToString("HH:mm:ss"); using (SqlConnection con2 = new SqlConnection(cs)) { string type = "Commercial"; string year = dd[2].ToString().Substring(dd[2].ToString().Length - 2); string HouseId = "CH1COM001" + rdr["rono"] + rdr["duration"] + "S" + dd[1] + dd[0] + year; string sql1 = "Insert into CTS(air_date,air_time,HouseNumber,rono,Title,duration,Slot,type,channel)Values('" + TextBox1.Text + "','" + startHeadlines_ + "','" + HouseId + "','" + rdr["rono"] + "','" + rdr["slug"] + "','" + rdr["duration"] + "','" + DropDownList1.SelectedValue.Remove(0, 3) + "','" + type + "','" + DropDownList3.SelectedValue.ToString() + "')"; con2.Open(); SqlCommand InsertCmd = new SqlCommand(sql1, con2); InsertCmd.ExecuteNonQuery(); con2.Close(); } } else { DateTime startTime = DateTime.ParseExact(DropDownList2.SelectedValue.ToString(), "HH:mm:ss", null); string startHeadlines = startTime.AddSeconds(210).ToString("HH:mm:ss"); using (SqlConnection con1 = new SqlConnection(cs)) { string type = "Commercial"; string year = dd[2].ToString().Substring(dd[2].ToString().Length - 2); string HouseId = "CH1COM001" + rdr["rono"] + rdr["duration"] + "S" + dd[1] + dd[0] + year; string sql = "Insert into CTS(air_date,air_time,HouseNumber,rono,Title,duration,Slot,type,channel)Values('" + TextBox1.Text + "','" + startHeadlines + "','" + HouseId + "','" + rdr["rono"] + "','" + rdr["slug"] + "','" + rdr["duration"] + "','" + DropDownList1.SelectedValue.ToString().Remove(0, 3) + "','" + type + "','" + DropDownList3.SelectedValue.ToString() + "')"; con1.Open(); SqlCommand InsertCmd = new SqlCommand(sql, con1); InsertCmd.ExecuteNonQuery(); con1.Close(); } } } con0.Close(); } } con.Close(); } }
Asp.net with c# , insert and update in save button
I am using one button named as Button 1. In Button 1 button I perform insert as well as update. I can insert a new row. But when I update the row I had a error on that: "ORA-00933: SQL command not properly ended ". My code is: protected void Button1_Click(object sender, EventArgs e) { string UserName = "UserName"; Session["UserName"] = lb1.Text; TextBox TextBox1 = (TextBox)FindControl("TextBox1"); Label label11 = (Label)FindControl("label11"); TextBox TextBox2 = (TextBox)FindControl("TextBox2"); TextBox TextBox3 = (TextBox)FindControl("TextBox3"); TextBox TextBox4 = (TextBox)FindControl("TextBox4"); DropDownList DropDownList3 = (DropDownList)FindControl("DropDownList3"); DropDownList DropDownList1 = (DropDownList)FindControl("DropDownList1"); TextBox TextBox5 = (TextBox)FindControl("TextBox5"); TextBox TextBox6 = (TextBox)FindControl("TextBox6"); DropDownList DropDownList2 = (DropDownList)FindControl("DropDownList2"); TextBox TextBox7 = (TextBox)FindControl("TextBox7"); TextBox TextBox8 = (TextBox)FindControl("TextBox8"); { con.Open(); OleDbDataAdapter da = new OleDbDataAdapter("select * from service_master where req_no='" + this.TextBox1.Text.ToString() + "'", con); DataSet ds = new DataSet(); da.Fill(ds); if (ds.Tables[0].Rows.Count > 0) { string sql1 = "update service_master set req_no='" + this.TextBox1.Text.ToString() + "' , req_dt='" + label11.Text.ToString() + "',req_by='" + Session["UserName"].ToString() + "', ser_cd='" + TextBox3.Text.ToString() + "',serv_desc= '" + TextBox4.Text.ToString() + "',serv_grp_cd='" + DropDownList3.SelectedItem.Value.ToString() + "',base_uom_cd= '" + DropDownList1.SelectedItem.Value.ToString() + "',sac_cd='" + TextBox5.Text.ToString() + "',ser_long_desc='" + TextBox6.Text.ToString() + "',tax_ind='" + DropDownList2.SelectedItem.Value.ToString() + "',active_ind= '" + TextBox7.Text.ToString() + "',del_ind='" + TextBox8.Text.ToString() + "' where req_no='" + this.TextBox1.Text.ToString() + "')"; OleDbCommand cmd = new OleDbCommand(sql1, con); cmd.ExecuteNonQuery(); WebMsgBox.Show("Data Successfully Updated"); } else { string sql = "insert into service_master(req_no,req_dt,req_by,ser_cd,serv_desc,serv_grp_cd,base_uom_cd,sac_cd,ser_long_desc,tax_ind,active_ind,del_ind ) values(" + this.TextBox1.Text.ToString() + ",'" + label11.Text.ToString() + "', '" + Session["UserName"].ToString() + "', '" + TextBox3.Text.ToString() + "','" + TextBox4.Text.ToString() + "','" + DropDownList3.SelectedItem.Value.ToString() + "','" + DropDownList1.SelectedItem.Value.ToString() + "','" + TextBox5.Text.ToString() + "','" + TextBox6.Text.ToString() + "','" + DropDownList2.SelectedItem.Value.ToString() + "','" + TextBox7.Text.ToString() + "','" + TextBox8.Text.ToString() + "')"; OleDbCommand com = new OleDbCommand(sql, con); com.ExecuteNonQuery(); WebMsgBox.Show("The data for request number" + TextBox1.Text + "is saved"); } con.Close(); } }
Your query should look something like this //insert query //string sql1 = "INSERT INTO Test(id, name) VALUES(#User_FirstName, #User_LastName)"; //update sample query string sql1 = "UPDATE Test SET User_FirstName=#User_FirstName, User_LastName=#User_LastName"; SqlCommand cmd = new SqlCommand(smt, _connection); cmd.Parameters.Add("#User_FirstName", FirstName.Text); cmd.Parameters.Add("#User_LastName", LastName.Text); Always use Parameters to preform any database actions. Using user input is very dangerous, look up sql injections.
Unable to save data into database
I am inserting some data into database using run-time SQL query, but before that i am checking is there any record exists or not. following is my code protected void btnSignUp_Click(object sender, EventArgs e) { if (Page.IsValid) { try { using (SqlConnection con = new SqlConnection(cs)) { string strgender = ""; if (Rb_Male.Checked) strgender = "Male"; else if (Rb_Female.Checked) strgender = "Female"; else { lblMsg.Text = "Please Select Gender"; lblMsg.ForeColor = Color.Red; } con.Open(); SqlCommand cmdcheck = new SqlCommand(); cmdcheck.CommandText = "select * from [Users] where E_Mail='" + #tb_Email.Text + "'"; cmdcheck.Connection = con; //cmd.Parameters.AddWithValue("#em", tb_Email.Text); SqlDataReader drd = cmdcheck.ExecuteReader(); if (drd.Read()) { lblEmail.Visible = true; lblEmail.Text = "Email Already Exsits"; lblMsg.ForeColor = Color.Red; lblMsg.Text = "Account not created!!!"; } else { string strcmd = "insert into Users values ('" + #tbName.Text + "','" + #tbSName.Text + "','" + #tb_Email.Text + "','" + #tb_Pass.Text + "','" + #DropDownDay.Text + "','" + #DropDownMonth.Text + "','" + #DropDownYear.Text + "','"+ strgender +"')"; SqlCommand cmd = new SqlCommand(strcmd, con); cmd.ExecuteNonQuery(); lblMsg.Text = "Account created sussecfully"; lblMsg.ForeColor = Color.Green; clearallfields(); } } } catch { lblMsg.ForeColor = Color.Red; lblMsg.Text = "Account not created!!!"; } } else { lblMsg.ForeColor = Color.Red; lblMsg.Text = " * Enter Required Field(s)"; } } The bellow part is working well in case if there no record associated with the particular email but if there is no record it goes to the else part and after executenonquery(); it goes to the catch part if (drd.Read()) { lblEmail.Visible = true; lblEmail.Text = "Email Already Exsits"; lblMsg.ForeColor = Color.Red; lblMsg.Text = "Account not created!!!"; } else { string strcmd = "insert into Users values ('" + #tbName.Text + "','" + #tbSName.Text + "','" + #tb_Email.Text + "','" + #tb_Pass.Text + "','" + #DropDownDay.Text + "','" + #DropDownMonth.Text + "','" + #DropDownYear.Text + "','"+ strgender +"')"; SqlCommand cmd = new SqlCommand(strcmd, con); cmd.ExecuteNonQuery(); lblMsg.Text = "Account created sussecfully"; lblMsg.ForeColor = Color.Green; clearallfields(); } } } catch { lblMsg.ForeColor = Color.Red; lblMsg.Text = "Account not created!!!"; } kindly help me out with this..
Your insert statement doesn't specify which columns you want to add to the Users table.Place a breakpoint on the following line: string strcmd = "insert into Users values ('" + #tbName.Text + "','" + #tbSName.Text + "','" + #tb_Email.Text + "','" + #tb_Pass.Text + "','" + #DropDownDay.Text + "','" + #DropDownMonth.Text + "','" + #DropDownYear.Text + "','"+ strgender +"')"; Take the value of strcmd and execute it in SQL Server Management Studio.You will see that it most likely fails.Fix the insert statement unti it works in SQL then copy it in your ASP.NET web application. Also change your catch block and inspect the exception you're getting: catch(Exception ex) { System.Diagnostics.Debugger.Break(); }
Overflow Error while inserting data in Access
protected void regsubmit_Click(object sender, EventArgs e) { OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\\Study\\Websites\\2\\database\\shoplocal.accdb"); con.Open(); OleDbCommand cmd = new OleDbCommand("insert into Registration values('" + txtfname.Text + "','" + txtemail.Text + "','" + txtpwd.Text + "','" + txtcnfpwd.Text + "','" + txtcntno.Text + "','" + txtaddrs.Text + "'," + Convert.ToInt32(txtpstlcode.Text) + ")", con); int chk = cmd.ExecuteNonQuery(); if (chk != 0) { lblmsg.Text = "Registration Successful"; } //OleDbCommand cmd1 = new OleDbCommand("delete * from Inward where Serial_no=" + tb_SLSserial_no.Text + "", con); //int chk1 = cmd1.ExecuteNonQuery(); con.Close(); I am getting an OleDb Overflow exception on int chk = cmd.ExecuteNonQuery(); whenever I click on submit button. Please help.
Check if a record exists in the database
I am using these lines of code to check if the record exists or not. SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') ", conn); int UserExist = (int)check_User_Name.ExecuteScalar(); But I am getting an error: Object reference not set to an instance of an object. I want to do: if (UserExist > 0) // Update record else // Insert record
ExecuteScalar returns the first column of the first row. Other columns or rows are ignored. It looks like your first column of the first row is null, and that's why you get NullReferenceException when you try to use the ExecuteScalar method. From MSDN; Return Value The first column of the first row in the result set, or a null reference if the result set is empty. You might need to use COUNT in your statement instead which returns the number of rows affected... Using parameterized queries is always a good practise. It prevents SQL Injection attacks. And Table is a reserved keyword in T-SQL. You should use it with square brackets, like [Table] also. As a final suggestion, use the using statement for dispose your SqlConnection and SqlCommand: SqlCommand check_User_Name = new SqlCommand("SELECT COUNT(*) FROM [Table] WHERE ([user] = #user)" , conn); check_User_Name.Parameters.AddWithValue("#user", txtBox_UserName.Text); int UserExist = (int)check_User_Name.ExecuteScalar(); if(UserExist > 0) { //Username exist } else { //Username doesn't exist. }
The ExecuteScalar method should be used when you are really sure your query returns only one value like below: SELECT ID FROM USERS WHERE USERNAME = 'SOMENAME' If you want the whole row then the below code should more appropriate. SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = #user)" , conn); check_User_Name.Parameters.AddWithValue("#user", txtBox_UserName.Text); SqlDataReader reader = check_User_Name.ExecuteReader(); if(reader.HasRows) { //User Exists } else { //User NOT Exists }
sqlConnection.Open(); using (var sqlCommand = new SqlCommand("SELECT COUNT(*) FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "'", sqlConnection)) { SqlDataReader reader = sqlCommand.ExecuteReader(); if (reader.HasRows) { lblMessage.Text ="Record Already Exists."; } else { lblMessage.Text ="Record Not Exists."; } reader.Close(); reader.Dispose(); } sqlConnection.Close();
MySqlCommand cmd = new MySqlCommand("select * from table where user = '" + user.Text + "'", con); MySqlDataAdapter da = new MySqlDataAdapter(cmd); DataSet ds1 = new DataSet(); da.Fill(ds1); int i = ds1.Tables[0].Rows.Count; if (i > 0) { // Exist } else { // Add }
I would use the "count" for having always an integer as a result SqlCommand check_User_Name = new SqlCommand("SELECT count([user]) FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') " , conn); int UserExist = (int)check_User_Name.ExecuteScalar(); if (UserExist == 1) //anything different from 1 should be wrong { //Username Exist }
try this public static bool CheckUserData(string phone, string config) { string sql = #"SELECT * FROM AspNetUsers WHERE PhoneNumber = #PhoneNumber"; using (SqlConnection conn = new SqlConnection(config) ) { conn.Open(); using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.AddWithValue("#PhoneNumber", phone); SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); if (reader.HasRows) { return true; // data exist } else { return false; //data not exist } } } }
Use try catch: try { SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') ", conn); int UserExist = (int)check_User_Name.ExecuteScalar(); // Update query } catch { // Insert query }
You can write as follows: SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') ", conn); if (check_User_Name.ExecuteScalar()!=null) { int UserExist = (int)check_User_Name.ExecuteScalar(); if (UserExist > 0) { //Username Exist } }
I was asking myself the same question, and I found no clear answers, so I created a simple test. I tried to add 100 rows with duplicate primary keys and measured the time needed to process it. I am using SQL Server 2014 Developer and Entity Framework 6.1.3 with a custom repository. Dim newE As New Employee With {.Name = "e"} For index = 1 To 100 Dim e = employees.Select(Function(item) item.Name = "e").FirstOrDefault() If e Is Nothing Then employees.Insert(newE) End If Next 2.1 seconds Dim newE As New Employee With {.Name = "e"} For index = 1 To 100 Try employees.Insert(newE) Catch ex As Exception End Try Next 3.1 seconds
sda = new SqlCeDataAdapter("SELECT COUNT(regNumber) AS i FROM tblAttendance",con); sda.Fill(dt); string i = dt.Rows[0]["i"].ToString(); int bar = Convert.ToInt32(i); if (bar >= 1){ dt.Clear(); MetroFramework.MetroMessageBox.Show(this, "something"); } else if(bar <= 0) { dt.Clear(); MetroFramework.MetroMessageBox.Show(this, "empty"); }
protected void btnsubmit_Click(object sender, EventArgs e) { string s = #"SELECT * FROM tbl1 WHERE CodNo = #CodNo"; SqlCommand cmd1 = new SqlCommand(s, con); cmd1.Parameters.AddWithValue("#CodNo", txtid.Text); con.Open(); int records = (int)cmd1.ExecuteScalar(); if (records > 0) { Response.Write("<script>alert('Record not Exist')</script>"); } else { Response.Write("<script>alert('Record Exist')</script>"); } } private void insert_data() { SqlCommand comm = new SqlCommand("Insert into tbl1(CodNo,name,lname,fname,gname,EmailID,PhonNo,gender,image,province,district,village,address,phonNo2,DateOfBirth,school,YearOfGraduation,exlanguage,province2,district2,village2,PlaceOfBirth,NIDnumber,IDchapter,IDpage,IDRecordNumber,NIDCard,Kankur1Year,Kankur1ID,Kankur1Mark,Kankur2Year,Kankur2ID,Kankur2Mark,Kankur3Year,Kankur3ID,Kankur3Mark) values(#CodNo,N'" + txtname.Text.ToString() + "',N'" + txtlname.Text.ToString() + "',N'" + txtfname.Text.ToString() + "',N'" + txtgname.Text.ToString() + "',N'" + txtemail.Text.ToString() + "','" + txtphonnumber.Text.ToString() + "',N'" + ddlgender.Text.ToString() + "',#image,N'" + txtprovince.Text.ToString() + "',N'" + txtdistrict.Text.ToString() + "',N'" + txtvillage.Text.ToString() + "',N'" + txtaddress.Value.ToString() + "','" + txtphonNo2.Text.ToString() + "',N'" + txtdbo.Text.ToString() + "',N'" + txtschool.Text.ToString() + "','" + txtgraduate.Text.ToString() + "',N'" + txtexlanguage.Text.ToString() + "',N'" + txtprovince1.Text.ToString() + "',N'" + txtdistrict1.Text.ToString() + "',N'" + txtvillage1.Text.ToString() + "',N'" + txtpbirth.Text.ToString() + "','" + txtNIDnumber.Text.ToString() + "','" + txtidchapter.Text.ToString() + "', '" + txtidpage.Text.ToString() + "','" + txtrecordNo.Text.ToString() + "',#NIDCard,'" + txtkankuryear1.Text.ToString() + "','" + txtkankurid1.Text.ToString() + "','" + txtkankurscore1.Text.ToString() + "','" + txtkankuryear2.Text.ToString() + "','" + txtkankurid2.Text.ToString() + "','" + txtkankurscore2.Text.ToString() + "','" + txtkankuryear3.Text.ToString() + "','" + txtkankurid3.Text.ToString() + "','" + txtkankurscore3.Text.ToString() + "')", con); flpimage.SaveAs(Server.MapPath("~/File/") + flpimage.FileName); string img = #"~/File/" + flpimage.FileName; flpnidcard.SaveAs(Server.MapPath("~/Tazkiera/") + flpnidcard.FileName); string img1 = #"~/Tazkiera/" + flpnidcard.FileName; comm.Parameters.AddWithValue("CodNo", Convert.ToInt32(txtid.Text)); comm.Parameters.AddWithValue("image", flpimage.FileName); comm.Parameters.AddWithValue("NIDCard", flpnidcard.FileName); comm.ExecuteNonQuery(); con.Close(); Response.Redirect("~/SecondPage.aspx"); //Response.Write("<script>alert('Record Inserted')</script>"); } }
Use the method Int.Parse() instead. It will work.
I had a requirement to register user. In that case I need to check whether that username is already present in the database or not. I have tried the below in C# windows form application(EntityFramework) and it worked. var result = incomeExpenseManagementDB.Users.FirstOrDefault(x => x.userName == registerUserView.uNameText); if (result == null) { register.registerUser(registerUserView.fnameText, registerUserView.lnameText, registerUserView.eMailText, registerUserView.mobileText, registerUserView.bDateText, registerUserView.uNameText, registerUserView.pWordText); } else { MessageBox.Show("User Alreay Exist. Try with Different Username"); }