Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

I am filling the textboxes on a windows form with records from an Access DB when the user selects a state in a combobox. I am using .executescalar. If a record in the DB is Null, I get an exception.

 

How can I tell the project that a DBNull = ""?

Posted

There are a variety of ways you could deal with this. Some of them would be:

 

1. Use IsNull in whatever SQL you're using to wrap your return value so that it returns empty string instead of null. For example, you might do something like this:

 

SELECT IsNull(fieldname, "") FROM tablename WHERE otherfield=somenum

 

(and I should mention that I don't have MS Access handy so I'm not positive on the MS SQL IsNull function - but I'm sure there is some way to convert a null to an empty string - I *think* that syntax is correct).

 

2. Another way to approach this in code would be to use a variable of type 'object' with your .ExecuteScaler, test that object to see if it's DBNull, and assign to your textbox accordingly, for ex: (C#):

 

//  This example is missing all the code that would actually setup
//    and properly execute the command...it's just a demo!
SqlCommand oCommand = new SqlCommand();

object oTest = oCommand.ExecuteScalar();

if (oTest != DBNull.Value)
{
   textBox1.Text = (string) oTest;
}
else
{
   textBox1.Text = "";

}

 

3. Use a Try/Catch to wrap your .ExcecuteScalar - but abusing Try/Catch isn't usually the best option if you can code to properly handle the expected behavior.

 

Paul

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...