12

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)));
2
  • Did you see what actual T-SQL is being executed? (ie with SQL Profiler). The ToString probably puts in the ''. But your saying there's a space ' ', which i cant see how it could happen. More likely sbcId != "", it's == " ". Commented Oct 12, 2010 at 9:36
  • Thanks RPM1984. I am using DB2. It seems that using ToString() was somehow translated into ' ' inside the database column. Commented Oct 12, 2010 at 9:49

8 Answers 8

25

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)

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks klausbyskov. That worked wonderfully ! =). Do you have any hint why was the column in database having value ' ' even if the string had ''.
Why is pictureBox1.Tag != null ? ImageOperations.ImageToBytes(pictureBox1.Image) : DBNull.Value throwing: Feature 'target-typed conditional expression' is not available in c# 7.3. Please use language version 9.0 or greater.
I had to do an if else for this in order to work. I'm using .net framework. Is this for .net core only?
10

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

3 Comments

Thanks Jon. You are right only problem being the casting into string.
Ah. Added something on the casting.
Thanks, that was also helpful. I +1 you as answer is already marked.
5

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

3 Comments

Thanks Preet although the problem is solved however I am puzzled why was the database column having ' ' even though the string was '' ?
what is the ddl for the table? Does it have a trigger?
@ZoHas , because the single quotes he used is text as declared by using the double quotes and tainted the result, when using string format you do not need to encapsulate the variable {0} in quotes... ie. Console.WriteLine("{0}", DBNull.Value.ToString()); would have been just fine.
1

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)));

1 Comment

That won't work with ternary operator but I fixed the problem. Thank you Pranay.
1

SQLString.Null should do the job just fine :)

Comments

1

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())); 

Comments

0

If you Insert a non string value in the access database you may write the insert query in this way

Insert into tableName (column1,column2) values (NULL,NULL);

But you want to insert null value in Short Text or Long Text field in access you may write the insert query in this way

Insert into tableName (column1, column2) values('','');

Comments

-3

your string like that

string value = "";

now add following line

 if (value == ""){

  value = "NULL";
     }

now insert in db and check you have null value their be logical

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.