Link to home
Start Free TrialLog in
Avatar of XGIS
XGISFlag for Australia

asked on

How do I check for NULL DB Records in this C# Code?

The following code is a static function used to calculate the NEXT ID created by the database.  The code needs to perform a basic initial check to ensure that if there are no records in the table it can take the appropriate action.  eg Make the First row 1.  eg Try/Catch or IF/Else.

public static int SiteIDMax()
{                                                    
int SiteID;
SiteID = Convert.ToInt32(ew_ExecuteScalar("SELECT max(SiteID) FROM DMPDB.DMP_Sites"))+ 1;  
//HttpContext.Current.Response.Write(Convert.ToInt32(SiteID));
return SiteID;
}

Open in new window

Avatar of kaufmed
kaufmed
Flag of United States of America image

Try:

object result = ew_ExecuteScalar("SELECT max(SiteID) FROM DMPDB.DMP_Sites");

if (result != DBNull.Value)
{
    SiteID = Convert.ToInt32(result);
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of XGIS
XGIS
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
For a SQL Server database, you can modify the query so it never returns NULL, like this:

SELECT ISNULL(max(SiteID),1) FROM DMPDB.DMP_Sites

Other database servers have similar functions.  I think for Oracle the function name is NVL.
Avatar of XGIS

ASKER

Hello Kaufmed.. thankyou for your time and logic... unfortunately it was a little bit more tricky working inside another application's implementation of C#.  The solution resolves the null issue and correctly assigns folders based on subsequent dependent code. I am sure this solution could be tidier..but "works" is more important than "tidy" for me.
Avatar of XGIS

ASKER

Hello  joriszwaenepoel... good call.. I have used this approach before and it is good based on the fact it eliminates messy codes.. I will give it a test, although my problem has been resolved. Cheers