Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Handling null values returned via SQL query 2

Status
Not open for further replies.

jasonp45

Programmer
Aug 23, 2001
212
US
How do I test for and handle a return of null in the following code?

Code:
                try
                {
                    OleDbConnection connection = new OleDbConnection(connectionString);
                    connection.Open();
                    OleDbCommand command = new OleDbCommand(SQL_Query, connection);
                    scalarReturned = command.ExecuteScalar().ToString();
                    command.Dispose();
                    connection.Close();
                }
                catch (Exception ex)
                {
                    
                }

This is part of a data-handling class I'm building, and I use this method for pulling single values from one of my lookup tables where the structure is fixed. It works fine; however I want to be able to handle when the query returns null...of course trying to convert null ToString() generates an error.

I suppose I could just trap that error, but I'd rather design it so no error is generated.

Thanks.
 
you could do something like
Code:
object scalarReturned = command.ExecuteScalar().ToString();

if(scalarReturned!= null)
{
  ....
}

// or if it is always an int that you are expecting
int myInt;
Int32.TryParse(scalarReturned.ToString(), out myInt);
if (myInt == 0)
{
    Console.WriteLine("Nothing returned");
}

Age is a consequence of experience
 
sorry this line should read
Code:
object scalarReturned = command.ExecuteScalar();
copy and paste error :(

Age is a consequence of experience
 
You could do a Convert.ToInt32 also. DbNull.value gets turned into a 0 when converted/tryparsed
 
Glad i could help, thanks for the star!

Age is a consequence of experience
 
Final working code:

Code:
object oScalarReturned = new Object();
oScalarReturned = command.ExecuteScalar();
if (oScalarReturned is DBNull || oScalarReturned == null)
    scalarReturned = "";
else
    scalarReturned = oScalarReturned.ToString();
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top