James
James

Reputation: 2246

Check for DBEmpty like DBNull in C#

I have a table Employee having a column JoiningDate of type DateTime.

I am fetching this value in asp.net.

I know to check DBnull we use dr["JoiningDate"] != DBNull.Value .

But if this JoiningDate is empty like '', which fetching it is making it like 1/1/1900.

What is the best way to check DB EMPTY in asp.net for a datetime column.

Details :

JoiningDate is a DateTime field..I made it empty string in stead of NULL..

And while fetching this in asp.net in dr["JoiningDate"] which is a datarow, it gave 1/1/1900.

Code Example

DataSet dsEmployee = null;
dsEmployee = Data.Select("SELECT * FROM Employee WHERE EmployeeID = '" + _id + "'");

DataRow drEmployee = dsEmployee.Tables[0].Rows[0];

if(drEmployee["JoiningDate"] != string.Empty)
{

}

Upvotes: 0

Views: 1245

Answers (5)

V4Vendetta
V4Vendetta

Reputation: 38210

If you say dr["JoiningDate"] is not returning null then

  • you are changing the value in the SELECT query
  • The default value of the column is set to 1/1/1900

Also please check where you insert the records in that case you would be passing null for that particular column so that it assumes the default value which is being returned

So you should rely on checking the condition by making a DateTime instance like new DateTime(1900,1,1) and then compare

Upvotes: 0

Ehsan
Ehsan

Reputation: 32681

You have to edit your check like this

if(dr["JoiningDate"] != DBNull.Value && !string.IsNullOrEmpty(Convert.ToString(dr["JoiningDate"])))
{
     //Your Code
}

Upvotes: 0

FlemGrem
FlemGrem

Reputation: 814

if(string.IsNullOrEmpty(........))
{

......

}

Upvotes: 0

A.T.
A.T.

Reputation: 26312

you can do something like this to check...

 if(  dr["JoiningDate"] != DBNull.Value && (DateTime)dr["JoiningDate"] != DateTime.Parse("1/1/1900")) {
//do...
}

Upvotes: 0

Microsoft DN
Microsoft DN

Reputation: 10020

Try this-

 if(!String.IsNullOrEmpty(Convert.ToString(dr["JoiningDate"])))
 {

 }

Upvotes: 1

Related Questions