Unable to save data into database - c#

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

Related

How can i insert from DataGridView to database when you have Columns with Date

I'm trying to enter data into the database from a DataGridView. I have 3 columns that contain Date.
When I try to insert to database I get the error:
Conversion failed when converting date and/or time from character string
With this I format the columns that show the date:
private void Import()
{
if (textBox4.Text.Trim() != string.Empty)
{
try
{
DataTable dt = GetDataTable(textBox4.Text);
dataGridView2.DataSource = dt.DefaultView;
dataGridView2.Columns[6].DefaultCellStyle.Format = "dd/mm/yyyy";
dataGridView2.Columns[8].DefaultCellStyle.Format = "dd/mm/yyyy";
dataGridView2.Columns[15].DefaultCellStyle.Format = "dd/mm/yyyy";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
With this part, I enter the data in the database from a DatagridView:
string constring = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
SqlConnection con = new SqlConnection(constring);
if (con.State == ConnectionState.Closed)
con.Open();
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
try
{
SqlCommand sqlCmd = new SqlCommand("insert into abonament (nr, serie, cui, client, sim, data_inst, activare, data_exp, telefon, nr_activat, nr_zile, ob, tip_client, email, datacurenta1, semnatura) values ('" + dataGridView1.Rows[i].Cells[0].Value + "','" + dataGridView1.Rows[i].Cells[1].Value + "','" + dataGridView1.Rows[i].Cells[2].Value + "','" + dataGridView1.Rows[i].Cells[3].Value + "','" + dataGridView1.Rows[i].Cells[4].Value + "','" + dataGridView1.Rows[i].Cells[5].Value + "','" + dataGridView1.Rows[i].Cells[6].Value + "','" + dataGridView1.Rows[i].Cells[7].Value + "','" + dataGridView1.Rows[i].Cells[8].Value + "','" + dataGridView1.Rows[i].Cells[9].Value + "','" + dataGridView1.Rows[i].Cells[10].Value + "','" + dataGridView1.Rows[i].Cells[11].Value + "','" + dataGridView1.Rows[i].Cells[12].Value + "','" + dataGridView1.Rows[i].Cells[13].Value + "','" + dataGridView1.Rows[i].Cells[14].Value + "','" + dataGridView1.Rows[i].Cells[15].Value + "')", con);
sqlCmd.ExecuteNonQuery();
MessageBox.Show("ok");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "error");
}
}
this was my solution
for (int i = 0; i < dataGridView2.RowCount; i++)
{
DateTime d1 = Convert.ToDateTime(dataGridView2.Rows[i].Cells[6].Value.ToString());
string format = "s";
DateTime d2 = Convert.ToDateTime(dataGridView2.Rows[i].Cells[8].Value.ToString());
DateTime d3 = Convert.ToDateTime(dataGridView2.Rows[i].Cells[15].Value.ToString());
try
{
SqlCommand sqlCmd = new SqlCommand("insert into abonament (nr, serie, cui, client, sim, data_inst, activare, data_exp, telefon, nr_activat, nr_zile, ob, tip_client, email, datacurenta1, semnatura) values ( #nr, #serie, #cui, #client, #sim, #data_inst, #activare, #data_exp, #telefon, #nr_activat, #nr_zile, #ob, #tip_client, #email, #datacurenta1, #semnatura)", con);
sqlCmd.Parameters.AddWithValue("#mode", "Add");
sqlCmd.Parameters.AddWithValue("#id", 0);
sqlCmd.Parameters.AddWithValue("#nr ", dataGridView2.Rows[i].Cells[1].Value);
sqlCmd.Parameters.AddWithValue("#serie ", dataGridView2.Rows[i].Cells[2].Value);
sqlCmd.Parameters.AddWithValue("#cui ", dataGridView2.Rows[i].Cells[3].Value);
sqlCmd.Parameters.AddWithValue("#client ", dataGridView2.Rows[i].Cells[4].Value);
sqlCmd.Parameters.AddWithValue("#sim ", dataGridView2.Rows[i].Cells[5].Value);
sqlCmd.Parameters.AddWithValue("#data_inst ", d1.Date.ToString(format));
sqlCmd.Parameters.AddWithValue("#activare ", dataGridView2.Rows[i].Cells[7].Value);
sqlCmd.Parameters.AddWithValue("#data_exp ", d2);
sqlCmd.Parameters.AddWithValue("#telefon ", dataGridView2.Rows[i].Cells[9].Value);
sqlCmd.Parameters.AddWithValue("#nr_activat ", dataGridView2.Rows[i].Cells[10].Value);
sqlCmd.Parameters.AddWithValue("#nr_zile ", dataGridView2.Rows[i].Cells[11].Value);
sqlCmd.Parameters.AddWithValue("#ob ", dataGridView2.Rows[i].Cells[12].Value);
sqlCmd.Parameters.AddWithValue("#tip_client ", dataGridView2.Rows[i].Cells[13].Value);
sqlCmd.Parameters.AddWithValue("#email ", dataGridView2.Rows[i].Cells[14].Value);
sqlCmd.Parameters.AddWithValue("#datacurenta1 ", d3);
sqlCmd.Parameters.AddWithValue("#semnatura ", dataGridView2.Rows[i].Cells[16].Value);
sqlCmd.ExecuteNonQuery();
}

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

How can i validate existing username in database using mysql in c#

I'm doing a registration form in c#
the code is working really well, but the the problem is even if the username
is already exist in the database it's still able to duplicate username.
How can i add a restriction for having a duplicate value for username?
So here is my code ps. i didn't add the exception because it's too long.
string condense = "datasource=localhost;port=3306;username=root;password=''";
string milk = "insert into empaccount.empinfo(IDNUMBER,email,username,password,firstname,lastname,cnumber) values ('" + this.idnumber.Text + "','" + email.Text + "','" + username.Text + "','" + password.Text + "','" + firstname.Text + "','" + this.lastname.Text + "','" + contactno.Text + "');";
MySqlConnection conDatabase = new MySqlConnection(condense);
MySqlCommand cmdDatabase = new MySqlCommand(milk, conDatabase);
MySqlDataReader myReader;
if (string.IsNullOrEmpty(idnumber.Text))
{
idnumber.Text = " Please generate an id number";
}
else
{
conDatabase.Open();
myReader = cmdDatabase.ExecuteReader();
MessageBox.Show("You're Registered!", "Successful!", MessageBoxButtons.OK, MessageBoxIcon.Information);
while (myReader.Read())
{
}
}
You need to add a unique limitation (constraint) to your table, using whatever database editor you used to create it. Then, catch an exception thrown by your application if the username is taken.
Basically, if there is some username already there, and you have a unique constraint on the username field in the table, your program will throw an exception when you try to add to it. Here is an example:
Also, if you are doing an insert query, you don't need to ExecuteRead(). Just do ExecuteNonQuery() and it will run the query without needing to return anything.
string condense = "datasource=localhost;port=3306;username=root;password=''";
string milk = "insert into empaccount.empinfo(IDNUMBER,email,username,password,firstname,lastname,cnumber) values ('" + this.idnumber.Text + "','" + email.Text + "','" + username.Text + "','" + password.Text + "','" + firstname.Text + "','" + this.lastname.Text + "','" + contactno.Text + "');";
MySqlConnection conDatabase = new MySqlConnection(condense);
MySqlCommand cmdDatabase = new MySqlCommand(milk, conDatabase);
MySqlDataReader myReader;
if (string.IsNullOrEmpty(idnumber.Text))
{
idnumber.Text = " Please generate an id number";
}
else
{
conDatabase.Open();
try {
cmdDatabase.ExecuteNonQuery();
}
catch {
//Username is taken
}
MessageBox.Show("You're Registered!", "Successful!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

error insert query after install application

i testing my program and when runed in vs without any error execute !
this is my code :
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conect = new OleDbConnection();
conect.ConnectionString = "provider=microsoft.jet.oledb.4.0;" + "data source=university.mdb;Jet OLEDB:Database Password=sa#a";
conect.Open();
OleDbCommand o1 = new OleDbCommand();
o1.Connection = conect;
if(button1.Text=="save")
o1.CommandText = "insert into check_user(name_user,pw_user)values('" + textBox1.Text + "','" + textBox2.Text + "')";
else
o1.CommandText = " select * from check_user WHERE (name_user = '" + textBox1.Text + "') and (pw_user = '" + textBox2.Text + "' )";
o1.ExecuteNonQuery();
if (button1.Text != "save")
{
if (o1.ExecuteScalar() == null)
MessageBox.Show("wrong user");
else
{
groupBox1.Visible = false;
menuStrip1.Visible = true;
}
}
else
{
groupBox1.Visible = false;
menuStrip1.Visible = true;
}
conect.Close();
}
but when execute after install app and run this query error occurs :
http://s4.picofile.com/file/8184692692/qq.png
any query select without error executed but query insert or delete occurs this error
please help me
You can't use NonQuery with a "Select". Try this
if(button1.Text=="save")
{
o1.CommandText = "insert into check_user(name_user,pw_user)values('" + textBox1.Text + "','" + textBox2.Text + "')";
o1.ExecuteNonQuery();
}
else
{
o1.CommandText = " select * from check_user WHERE (name_user = '" + textBox1.Text + "') and (pw_user = '" + textBox2.Text + "' )";
o1.ExecuteQuery();
}​

Null Reference Exception when Clicking a button in ASP.NET Webforms

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" ... />

Categories

Resources