Answered by:
Object reference not set to an instance of Object

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.
- 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
-
User-158764254 posted
give this a read:
Sunday, July 14, 2019 12:27 PM -
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.
- 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 -
User1120430333 posted
You made the same post in two ASP.NET forums. The moderators kind of don't like that.
Sunday, July 14, 2019 1:35 PM