Alyasar Abdulsattar Khatri Alyasar Abdulsattar Khatri - 9 months ago 60
C# Question

Operator '==' cannot be applied to operands of type 'string' and 'system.dbnull'

I am retrieving data from database for that i am using following code.

compname.Text = mRS.Fields["CompName"].Value == DBNull.Value ? "" : mRS.Fields["CompName"].Value.ToString();

But on run time it is giving me error "Operator '==' cannot be applied to operands of type 'string' and 'system.dbnull'"

Why this error is coming?

Answer Source

Because mRS.Fields["CompName"].Value is a value of that field and is of type string and DBNull.Value is of type DBNull.

You should compare DBNull.Value to the field itself (and not its value), like this:

compname.Text = DBNull.Value.Equals(mRS.Fields["CompName"]) ? "" : mRS.Fields["CompName"].Value;