Unable to pass object of type "System.DBNull" to enter "System.String"

I have datable code to create a string that 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 data is

NULL
0
138
337
1666
1680
2511
8113

You see that there is "NULL" to cause the error "Unable to pass an object of type" System.DBNull "to enter" System.String ". How to fix this?

+3
source share
3 answers

Try the following:

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

Change your loop:

foreach(var obj in row.ItemArray)
{
    if(obj is string) sb.Append(obj as string);
}
+1
source
            if(!row.IsNull("column"))
            {
                foreach (string str in row.ItemArray)
                {
                    sb.Append(str);
                }                
            }
+1
source

All Articles