I’m using Oledb as my database and I’m trying to update the “Status” column in my db whenever a user taps in and taps out. So it goes like this..
When a user taps, it will query the “Status” column of the db whether it was “IN”, “OUT” or blank previously. When queried to be “IN”, the status will be set to “OUT” currently and vice versa. The updatings are all working exactly the way I want except that the warning “NullReferenceException was unhandled” that keeps appearing at this line everytime I run it and I can’t continue running further: str = cmd1.ExecuteScalar().ToString();
I’m very new to C# and it’d be good if someone can explain to me in detail how I can fix this. Thank you!
// prepare command string
string selectString = @"SELECT Status FROM jiahe where [Tag ID] = '" + textBox1.Text + "'";
// 1. Instantiate a new command with command text only
OleDbCommand cmd = new OleDbCommand(selectString, objConnection);
// 2. Set the Connection property
cmd.Connection.Open();
// 3. Call ExecuteNonQuery to send command
string str = cmd.ExecuteScalar().ToString();
cmd.Connection.Close();
if (str.Length == 2 || str.Length == 0)
{
//MessageBox.Show("Status: " + str);
// prepare command string
string updateString = @"update jiahe set Status = 'OUT' where [Tag ID] = '" + textBox1.Text + "'";
// 1. Instantiate a new command with command text only
OleDbCommand cmd1 = new OleDbCommand(updateString, objConnection);
// 2. Set the Connection property
cmd1.Connection.Open();
// 3. Call ExecuteNonQuery to send command
str = cmd1.ExecuteScalar().ToString();
MessageBox.Show("Status: OUT");
cmd1.Connection.Close();
}
else
{
//string str1 = cmd2.ExecuteScalar().ToString();
//MessageBox.Show("Status: " + str);
// prepare command string
string updateString = @"update jiahe set Status = 'IN' where [Tag ID] = '" + textBox1.Text + "'";
// 1. Instantiate a new command with command text only
OleDbCommand cmd1 = new OleDbCommand(updateString, objConnection);
// 2. Set the Connection property
cmd1.Connection.Open();
// 3. Call ExecuteNonQuery to send command
//string str1 = cmd2.ExecuteScalar().ToString();
str = cmd1.ExecuteScalar().ToString();
MessageBox.Show("Status: IN");
cmd1.Connection.Close();
}
}
You intend to call
ExecuteNonQuerybut you wroteExecuteScalarPlease check your line
I guess it should be