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

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;
Comments