Skip to content

How can I check for a null value while loading a list with a reader??

Jason

Asked Jan 22, 2007, 1:15 PM EST1 answer
Share
LinkedInX
The description field is null in my database and whenever the following code tries to load a list it throws an exception, I have searched all over and tried several things I thought would work.  I am new to C# coming from VB so forgive my ignorance.  Thank you for your time!

Java
public static List<Subcategories> GetSubcategories(int SubgroupID)
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["XXX"].ConnectionString))
{
using (SqlCommand command = new SqlCommand("GetSubcategories", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("@SubgroupID", SubgroupID));
connection.Open();
List<Subcategories> list = new List<Subcategories>();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{

Subcategories temp = new Subcategories(

(int)reader["SubCategoryId"],

(int)reader["SubgroupID"],

(string)reader["Title"],

(string)reader["Manager"],

(string)reader["Description"]);   <----- THIS LINE IS WHERE THE FAILUER OCCURS!

Code
list.Add(temp);
}
}
return list;
}
}
}

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0


    if( reader["Description"] != null)
    {
       string description = reader["Description"].ToString()
    }

    hope this helps

    0