user2979362 user2979362 - 1 year ago 81
C# Question

ExecuteScalar() error

I want to create a Log In form with C#. If the username and password is correct, I do not get an error, but if it's wrong then I get an error in this line:

int count = Convert.ToInt32(cmd.ExecuteScalar().ToString());

log in form code:

if (textBox1.Text != "" & textBox2.Text != "")
SqlCeCommand cmd = new SqlCeCommand("SELECT id FROM users WHERE Login = '" + textBox1.Text + "' AND Password = '" + textBox2.Text + "'", conn);
int count = Convert.ToInt32(cmd.ExecuteScalar().ToString());
if (count > 0)
SqlCeDataReader reader = cmd.ExecuteReader();
int logged_id = Convert.ToInt16(reader["id"]);
SqlCeCommand cmd1 = new SqlCeCommand("SELECT Login, Sex, Weight, Height, Age, PhyActi FROM vartotojai WHERE ID = '"+ logged_id +"'",conn);
SqlCeDataReader reader1 = cmd1.ExecuteReader();
textBox9.Text = Convert.ToString(reader1["Sex"]);
textBox10.Text = Convert.ToString(reader1["Weight"]);
textBox12.Text = Convert.ToString(reader1["Height"]);
textBox11.Text = Convert.ToString(reader1["Age"]);
textBox13.Text = Convert.ToString(reader1["Phyacti"]);
panel1.Visible = false;
dataGridView1.Visible = false;
MessageBox.Show("Loggen In!");
toolStripStatusLabel1.Text = "Welcome, " + Convert.ToString(reader1["Login"]);
MessageBox.Show("User Not Found!");

Answer Source

If you look at the ExecuteScalar help in MSDN HERE

then you will notice that the return value in case the resultset is empty is a null reference.

In your code, when username and/or password is wrong then you are not getting any value i.e. a null reference is returned. Now, you are trying to convert a null value to an Integer and you get the error.

What you should do is that you should get the return value in a system.object variable and check if it is null. If not, then convert it to Integer else show the message "User not found.".