Dataset Inserting Empty instead of Null

E

Earl

VS2005 app with SQL2k and stored proc.

Using a strongly-typed dataset, I've noticed that on Insert, my columns that
should be null are instead showing as empty. For example, using either of
these three example pieces of code with the textbox remaining empty, I still
get an empty string where the column in the new row should remain null.

EXAMPLE 1
if (txtMiddle.Text != null)
{
rowContact.MiddleName = txtMiddle.Text;
}

EXAMPLE 2
if (txtMiddle.Text != null)
{
rowContact.MiddleName = txtMiddle.Text;
}
else
{
rowContact.SetMiddleNameNull();
}

EXAMPLE 3
if (txtMiddle.Text != null | txtMiddle.Text != "")
{
rowContact.MiddleName = txtMiddle.Text;
}
else
{
rowContact.SetMiddleNameNull();
}
 
S

Stephany Young

I think that you will find that your test for (txtMiddle.Text != null) will
always be false because the content of an empty TextBox is actually an empty
string.

The test needs to be either (txtMiddle.Text.Trim().Length != 0) or
(txtMiddle.Text.Trim() != string.Empty).

You are correct that you need to set the value of the column to a NULL that
the database can understand. I prefer to use System.DbNull.Value.

One way to do it is:

txtMiddle.Text = txtMiddle.Text.Trim();
rowContact.MiddleName = (txtMiddle.TextLength == 0 ? DbNull.Value :
txtMiddle.Text);
 
E

Earl

One thing I did not note, this is a strongly typed dataset in 2.0 .Net, so
you get the typed properties to set a column null (.SetMiddleNameNull), thus
the use of that versus DbNull which I had used in previous apps.
 

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