Saturday, October 5, 2013

How do I return a value to a sqldatareader if value is null? asp net c#

int CountryId;
SqlDataReader reader = ...........
 
if (reader.HasRows)
{
 reader.Read();
 CountryId = reader.GetInt16(reader.GetOrdinal("CountryId"));
 
But if CountryId is null it will throw an exception so use safe method

CountryId = !string.IsNullOrWhiteSpace(reader["CountryId"].ToString()) ? 
Convert.ToInt32(reader["CountryId"]) : -1; 

That is it

No comments:

Post a Comment