简体   繁体   中英

Object cannot be cast from DBNull to other types

I am trying to save the gridview data into the database. To decide if it should be an Insert or update, i need to find out if the Order_SelectionID exists. Foreach Gridview row, i am trying to use the statement like the following in C# using Asp.Net.

foreach (GridViewRow row in grdFavoriteMerchant.Rows)
    {
        if (grdFavoriteMerchant.DataKeys[row.RowIndex]["Order_SelectionID"].ToString() != "")
        {

If Order_SelectionID exists and not a NUll or zero, i will have to "Insert", else an "Update".

This statement gives me an exception

"Object cannot be cast from DBNull to other types."

everytime when i am supposed to use an Insert. How can i correct it?

Why not compare directly to DBNull.Value ?

if(grdFavoriteMerchant.DataKeys[row.RowIndex]["Order_SelectionID"]
                                     ==  DBNull.Value)

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