问题
I have read several posts on this online, but none of them have resolved my issue. Most of the questions posted online point me towards checking Dbnull values from the database and I am doing that in the code.
Here's the code where the exception is thrown:
int rowNum = Convert.ToInt32(dataTable.Rows[r][dataTable.Columns.Count - 2]);
Here's the code where I am checking for the dbnull values:
for (int r = 0; r < dataTable.Rows.Count - 1; r++) //rows
{
for (int c = 1; c < dataTable.Columns.Count - 2; c++)
{
object val = dataTable.Rows[r][c];
if (!val.Equals(DBNull.Value))
{
haveValues = true;
}
}
}
Here I am reading the values from the excel spreadsheet.
Please point me in the right direction. Thanks in advance.
Dimpy
回答1:
check for DbNull before calling Convert.ToInt32: as you have seen, this will raise an exception if the value is DbNull. something like:
object x = *value from db*
int y;
if (x != DbNull.Value)
y= Convert.ToInt32(x);
else
//handle null somehow
回答2:
You can also check:
dataTable.Rows[r].IsNull(c)
c
can be the index, the column name or the DataColumn
回答3:
for (int c = 1; c < dataTable.Columns.Count - 2; c++)
You don't check for count-2 so dataTable.Rows[r][dataTable.Columns.Count - 2] could be DBNull and your Convert fails
回答4:
I tend to do if(varFromSQL.ToString()!="") and then carry on with my business. Works like a charm every time. And then if i need to System.Convert.ToSomething() i can do that.
回答5:
You can try like this: DBNull.Value.Equals(dataTable.Rows[r][c]) if you want the index of the column you can use row[dataTable.Columns.IndexOf(col)] inside the foreach.
for (int r = 0; r < dataTable.Rows.Count - 1; r++) //rows
{
foreach (DataColumn col in dataTable.Rows[r].Table.Columns)
{
if (!DBNull.Value.Equals(dataTable.Rows[r][col.ColumnName]))
{
haveValues = true;
}
}
And Please provide more information about the type of exception, maybe the error is accessing an invalid index => int rowNum = Convert.ToInt32(dataTable.Rows[r][dataTable.Columns.Count - 2]); Why you use ...Columns.Count - 2 ?, What about if the count of columns is equals to 1 ?
I Hope to this helps.
Regards
来源:https://stackoverflow.com/questions/33740382/c-object-cannot-be-cast-from-dbnull-to-other-types