2

I need to check if a record is saved into database or not. If it was saved in database open another form, else show a message that it is not in database.
If the record is not in database I get this error Object reference not set to an instance of an object.
This is my code please help me to find the error here:

string cmdStr = "Select NO from COM_LIST_EXPORT where NO = '" + txtNO.Text + "'";
SqlCommand cmd = new SqlCommand(cmdStr, CN);
int count = (int)cmd.ExecuteScalar();
if (count == Convert.ToInt32(txtNO.Text))
{
    Archive_Sader dd = new Archive_Sader();
    dd.Show();
}

else
{
    MessageBox.Show("please save first");
}
Noctis
  • 11,507
  • 3
  • 43
  • 82
user2746526
  • 97
  • 4
  • 12

2 Answers2

7

ExecuteScalar returns null when no records found.

So when trying to cast null -> int you get a NullReferenceException

Try this instead.

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

Convert.ToInt32 will return 0 when parameter is null.

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
2

From SqlCommand.ExecuteScalar

Return Value

The first column of the first row in the result set, or a null reference if the result set is empty.

That's why when there is no row as a result, you actually try to convert null to Int32.

Looks like you need to change your line like;

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

Because Convert.ToInt32 returns 0 when parameter is null.

Return Value

A 32-bit signed integer that is equivalent to the number in value, or 0 (zero) if value is null.

And you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.

For example;

string cmdStr = "Select NO from COM_LIST_EXPORT where NO = @NO";
SqlCommand cmd = new SqlCommand(cmdStr, CN);
cmd.Parameters.AddWithValue("@NO", txtNO.Text);
...
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364