locked
Object reference not set to an instance of Object RRS feed

  • Question

  • User-797751191 posted

    Hi

       When no record if found i get above error . I want that if no record found then message should get displayed 'No record found'.

    In Status it shows Null

                    using (SqlCommand cmd = new SqlCommand("SELECT Status FROM test3 Where [No]=@INo", con))
                    {
                        cmd.CommandType = CommandType.Text;
                        cmd.Parameters.AddWithValue("@INo", txtNo.Text.Trim());
                        Status = cmd.ExecuteScalar().ToString();

    Thanks

    Sunday, July 14, 2019 12:04 PM

Answers

  • User475983607 posted

    Hi

       When no record if found i get above error . I want that if no record found then message should get displayed 'No record found'.

    In Status it shows Null

                    using (SqlCommand cmd = new SqlCommand("SELECT Status FROM test3 Where [No]=@INo", con))
                    {
                        cmd.CommandType = CommandType.Text;
                        cmd.Parameters.AddWithValue("@INo", txtNo.Text.Trim());
                        Status = cmd.ExecuteScalar().ToString();

    Thanks

    ExecuteScalar returns and object as illustrated in the docs.  If your SQL design can return NULL then you need to check for NULL before using .ToString().

    object result = cmd.ExecuteScalar();
    if(result == null) 
    {
       // No record found
    }

    ExecuteScalar() reference docs.

    https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.executescalar?view=netframework-4.8



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, July 14, 2019 12:35 PM
  • User1120430333 posted

    Well, you can do a null value check.

    If (Status == null)
    {
      //do one thing
    }
    else
    {
      //do something else if not null
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, July 14, 2019 1:23 PM

All replies