简体   繁体   中英

C#: Object cannot be cast from DbNull to other types

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

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

You can also check:

dataTable.Rows[r].IsNull(c)

c can be the index, the column name or the DataColumn

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM