views:

44

answers:

5

how to pass sql parameter as null value in to integer data type variable ?

        StockBO sBO = new StockBO();
        sBO.Mode = 2;
        if (ddcmpanyname.SelectedIndex != 0)
        {
            sBO.Client_id = Convert.ToInt16(ddcmpanyname.SelectedValue);
        }
        else
        {
            sBO.Client_id = Convert.ToInt16(DBNull.Value);//Object cannot be cast from DBNull to other types.
       sBO.Client_id =DBNull.Value;//Cannot implicitly convert type 

        }
        ds=_StockController.StockGet(sBO);

i changed the code like this it gives error like i my comment check else part

+1  A: 

It's not entirely clear what you mean. If you're trying to pass a null value in a SQL parameter, you should use DBNull.Value as the value for your SqlParameter (or whatever type you're using). If you want to represent a nullable integer in C#, use int? (or Nullable<int> - they're the same thing).

You can't store a null value in a normal non-nullable value type variable. Nullable value types are still structs, but they wrap the non-nullable type and add a Boolean value to indicate whether it's a "real" value or null. C# adds syntactic sugar around it, allowing you to use the null literal for assignments, various conversions, lifted operators etc:

int? value = 5;
value = null;
if (value == null)
{
    ...
}

If that doesn't help, please give us more information about exactly what you're trying to do.

EDIT: Okay, so it looks like StockBO.Client_id should be of type short? - but then that won't allow DBNull.Value to be set directly. You should use null to set the client ID to the null value. Whenever you translate between objects and SQL parameters and results, you'll need to perform that kind of conversion yourself - if you find yourself doing this regularly, work out some helper methods to make it easier for you.

Of course, if you start using LINQ to SQL or anything like that, you don't need to worry about DBNull.Value - LINQ providers tend to support nullable value types directly.

Jon Skeet
I am very proud to see post..thanks ma i have updated my question please do check it
Ayyappan.Anbalagan
@Ayyappan: I've edited my answer.
Jon Skeet
Thank u Mr jon skeet
Ayyappan.Anbalagan
+1  A: 

from SQL to C# >

int number;
Int32.TryParse(paramvalue, out number);

from C# to SQL >

add DBNull to your parameter

riffnl
A: 

Try DBNull.Value; Like for instance:

dbParamId.Value = (object)MyID ?? DBNull.Value;
KMan
A: 

Considering ParamValue contains the result of the query as an integer or a DBNull.Value, I'm casting it to int? this way:

var Result = ParamValue as int?;

To determine whether Result is null, do check Result.HasValue. Otherwise, use it as a usual integer, or Result.Value

controlbreak
+1  A: 

Try this,

else
    {
        sBO.Client_id = System.Data.SqlTypes.SqlInt32.Null;
    }
Pandiya Chendur