Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert null into database?

Tags:

c#

asp.net

c#-2.0

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)));
like image 884
Zo Has Avatar asked Oct 12 '10 09:10

Zo Has


2 Answers

I prefer to use an extension method to handle instead of multiple if statements. This allows you to account for null or empty string values. Also allows it to be reusable.

    public static object GetDBNullOrValue<T>(this T val)
    {
        bool isDbNull = true;
        Type t = typeof(T);

        if (Nullable.GetUnderlyingType(t) != null)
            isDbNull = EqualityComparer<T>.Default.Equals(default(T), val);

        else if (t.IsValueType)
            isDbNull = false;

        else if (t == typeof(string) && val != null)
        {
            string temp = val as String;
            isDbNull = (temp == String.Empty);
        }

        else
            isDbNull = (val == null);

        return isDbNull ? DBNull.Value : (object)val;
    }

Then you could use

     Parameters.Add(new OleDbParameter("EMPID", sbcId.GetDBNullOrValue())); 
like image 199
JMIII Avatar answered Sep 19 '22 05:09

JMIII


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)

like image 35
Klaus Byskov Pedersen Avatar answered Sep 21 '22 05:09

Klaus Byskov Pedersen