Search code examples
c#stringdatatabledatarow

Unable to cast object of type 'System.DBNull' to type 'System.String'


I have a datable code to generate a string, which is sb.ToString().

DataTable dt = dbaccess.GetDataTable("TEST"); // get datatable
List<DataRow> drlist = dt.AsEnumerable().ToList(); // each row only has one element.
StringBuilder sb = new StringBuilder(); 
foreach (DataRow row in drlist)
{
    foreach (string str in row.ItemArray)
    {
        sb.Append(str);
    }
}

The datatable is

NULL
0
138
337
1666
1680
2511
8113

You see that there is "NULL" to cause the error "Unable to cast object of type 'System.DBNull' to type 'System.String'. How to fix it?


Solution

  • Try this:

    foreach (object str in row.ItemArray) 
    { 
        if (DbNull.Value.Equals(str))
           sb.Append("NULL");
        else
           sb.Append(str.ToString()); 
    }