tags:

views:

101

answers:

5

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)));
+1  A: 

You should be able to use DbNull.Value or null directly

vc 74
+1  A: 

Try below by removing ToString() after DBNull.Value

string sbcId = gvTest.DataKeys[gr.RowIndex]["myColumn"].ToString();
 insgnp.Parameters.Add(new OleDbParameter("EMPID", (sbcId==""?DBNull.Value:sbcId)));
Pranay Rana
That won't work with ternary operator but I fixed the problem. Thank you Pranay.
Popo
+3  A: 

Use DBNull.Value, not DBNull.Value.ToString. (With other parameter collection types in .NET just using null would also work, but I'm not 100% sure about OleDbParameter).

As for the tertiary operator. Don't cast to string, but cast the string to object:

sbcId=="" ? DBNull.Value : (object)sbcId
Jon Hanna
Thanks Jon. You are right only problem being the casting into string.
Popo
Ah. Added something on the casting.
Jon Hanna
Thanks, that was also helpful. I +1 you as answer is already marked.
Popo
+2  A: 

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)

klausbyskov
Thanks klausbyskov. That worked wonderfully ! =). Do you have any hint why was the column in database having value ' ' even if the string had ''.
Popo
+2  A: 

You need to use DBNull.Value not DBNull.Value.ToString()

DBNull.Value.ToString() is ''

This program gives

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("'{0}'", DBNull.Value.ToString());
        }
    }
}

alt text

Preet Sangha
Thanks Preet although the problem is solved however I am puzzled why was the database column having ' ' even though the string was '' ?
Popo
what is the ddl for the table? Does it have a trigger?
Preet Sangha
nope it is a simple insert statement with parameters.
Popo