Nulls an string

T

tshad

How do you handle nulls and strings from Sql to a string value?

On a web page if the type is a VarChar going to a textbox, you can:

textbox.text = user["stringValue"];

But if an int value that could be null you need to test for DBNull.Value
first and just ignore it if it is a Null. This works fine for updating as
you can tell if the int is supposed to be null or not (if textbox empty -
null).

if I am reading into an int it is a pain as you have to make up a value for
null (usually 0, but not always) -as we talked about in another post:

int param7;
if (parameters[7] == DBNull.Value)
{
// ... handle null case ...
param7 = -1;
}
else
{
param7 = (int)(parameters[7]);
}

How do I handle a string?

I had thought, I wouldn't have to worry about it (like the textbox.text),
but that is not the case I still have to:

string param7;
if (parameters[7] == DBNull.Value)
{
// ... handle null case ...
}
else
{
param7 = (string)(parameters[7]);
}

What is the best way to handle a string? Make it "" if null?

Of course the problem is the same as int, if you send the data back to Sql,
you will now have a value in that field, that you may not want. You may
want it null. Dates are a good example here. I may not want a date in a
DateTerminated field if the person is still working.

Thanks,

Tom
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

What is the best way to handle a string? Make it "" if null?

Well, you can assign it to null, or just assign a predefined value,
depending of your app, example, I bind such a table to a datagrid, what I do
in that case is if the column is DBNull I show a "N/A" to the user.

Of course the problem is the same as int, if you send the data back to
Sql, you will now have a value in that field, that you may not want. You
may want it null. Dates are a good example here. I may not want a date
in a DateTerminated field if the person is still working.

The only solution using C# 1.X is either wrapping the int or DateTime in a
type that does support null, or using a predefined value as "null" ( -1 ,
DateTime.MinValue )


cheers,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top