Deepak Jain
Deepak Jain

Reputation: 137

Retrieving single value from datatable how to check NULL

I am trying to compare the value of a row esmcost with psmcost of table wsmtbl but esmcost cost value is null due to which I am getting the following error:

Operator '<>' is not defined for type 'DBNull' and type 'DBNull'

Is there any way to change the null value to zero?

This is the C# code

ds.Tables["wsmtbl"].Rows[0]["esmcost"] <> ds.Tables["wsmtbl"].Rows[0]["psmcost"]

Upvotes: 0

Views: 213

Answers (2)

IrishChieftain
IrishChieftain

Reputation: 15253

Try the following.

Decimal esmcost;
if (ds.Tables["wsmtbl"].Rows[0]["esmcost"] == DBNull.Value)
    esmcost = 0.00;
else
    esmcost = Convert.ToDecimal(ds.Tables["wsmtbl"].Rows[0]["esmcost"]);

Decimal psmcost;
if (ds.Tables["wsmtbl"].Rows[0]["psmcost"] == DBNull.Value)
    psmcost = 0.00;
else
    psmcost = Convert.ToDecimal(ds.Tables["wsmtbl"].Rows[0]["psmcost"]);

if (esmcost != psmcost)
{
    ...
}

One could use the ternary operator syntax but I chose the above for readability reasons. For example:

Decimal esmcost = ds.Tables["wsmtbl"].Rows[0]["esmcost"]
    == DBNull.Value ? 0.00 : Convert.ToDecimal(ds.Tables["wsmtbl"].Rows[0]["esmcost"]);

Upvotes: 1

sanatsathyan
sanatsathyan

Reputation: 1763

Try this,

if(ds.Tables["wsmtbl"].Rows[0]["esmcost"] == DBNull.Value)
{
   ds.Tables["wsmtbl"].Rows[0]["esmcost"] = 0;
}

 ds.Tables["wsmtbl"].Rows[0]["esmcost"] != ds.Tables["wsmtbl"].Rows[0]["psmcost"];

Upvotes: 0

Related Questions