How to insert null into database?

Zo Has picture Zo Has · Oct 12, 2010 · Viewed 52.8k times · Source

Hi I am trying to insert null in a database column depending on a gridview datakeys value (if being "" insert null into database) However, I am getting a space ' ' inside the database column.

string sbcId = gvTest.DataKeys[gr.RowIndex]["myColumn"].ToString();
 insgnp.Parameters.Add(new OleDbParameter("EMPID", (sbcId==""?DBNull.Value.ToString():sbcId)));

Answer

Klaus Byskov Pedersen picture Klaus Byskov Pedersen · Oct 12, 2010

You have to rewrite your code:

if(string.IsNullOrEmpty(sbcId))
    Parameters.Add(new OleDbParameter("EMPID", DBNull.Value)); 
else
    Parameters.Add(new OleDbParameter("EMPID", sbcId)); 

The problem with the ternary if statement that you have is that its returntype must always be the same, which is why you cannot use it (string and DbNull.Value are not compatible)