Reputation: 53
When I call the function I receive an error that says data is null. This method or property cannot be called on null values.
I believe the error exists at this line
Error = id = rd.GetString(0);
The code I am using is below
public string MaxId()
{
string id="";
con.Open();
string sql = "SELECT MAX(CustID) FROM Customer";
SqlCommand cmd = new SqlCommand(sql,con);
SqlDataReader rd = cmd.ExecuteReader();
while(rd.Read())
{
id = rd.GetString(0);
}
con.Close();
return id;
}
How do I get a string from the DataReader that may be null?
Upvotes: 1
Views: 11503
Reputation: 124696
If your Customer table is empty, then the query will return NULL.
In this case rd.GetString(0)
will throw, since GetString
can not return a NULL value.
You could do something like:
if (rd.IsDBNull(0))
{
id = null;
}
else
{
id = rd.GetString(0);
}
Upvotes: 15