0
votes

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?

1
FYI OP, you are not checking if Order_SelectionID is null or zero in your code above. You are checking to see if it is an empty string; which is different than the two examples you noted above. - Brian

1 Answers

5
votes

Why not compare directly to DBNull.Value?

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