getting count of an existence in a table RRS feed

  • Question

  • hi,
    i wanna to get count of an existence in a table with "select count..." statement but it errors that return null.
    this is my code:

    SqlCommand mysql2 = new SqlCommand(string.Format("SELECT count(usercode) as counter FROM tbltemp_permission WHERE (usercode = N'{0}')", Session["usercode"]), SqlConnection);
                    String counter = (mysql2.ExecuteScalar() as String);
                    if (counter.CompareTo("0") == 0)

    and this is the specified error:

    System.NullReferenceException: Object reference not set to an instance of an object.


    Sunday, June 3, 2007 6:08 AM

All replies

  • Using the Northwind db as an example:

    Code Snippet

    string sql = string.Format("SELECT COUNT(*) AS count FROM Customers");
    SqlCommand cmd = new SqlCommand(sql, conn);

    object result = cmd.ExecuteScalar();

    Notice that the result is an Int32..  So if you do String counter = mysql2.ExecuteScalar() as String you will assign null to counter... And then you try to call CompareTo on a null (which fails)...

    Code Snippet

    int counter = (int) mysql2.ExecuteScalar();
    if (counter == 0)

    Sunday, June 3, 2007 3:21 PM