nullreferenceexception from ExecuteScalar()

  Kiến thức lập trình

i really don’t know what to write here. i was just coding and this stuff happened.

connection.Open();
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "select count(*) from Categories where Name = @Name group by CategoryID";
cmd.Parameters.AddWithValue("@Name", categoryName);
int count = (int)cmd.ExecuteScalar();

it errors at

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

i’m expecting it to return a value of 1, since there’s 1 row in the Categories table. however, it just throws an exception.

New contributor

Unseens is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT