Tom Gullen
Tom Gullen

Reputation: 61755

ASP.net #c compare to null not working

       Artwork.ArtworkMyAvailableVotesDataTable dtCommon2 = new Artwork.ArtworkMyAvailableVotesDataTable();
        using (ArtworkTableAdapters.ArtworkMyAvailableVotesTableAdapter artworkTemplates = new ArtworkTableAdapters.ArtworkMyAvailableVotesTableAdapter())
        {
            artworkTemplates.Fill(dtCommon2, Master.loginData.loggedInUser.ID);
        }

        for (int i = 0; i < dtCommon2.Count; i++)
        {
            string voteStatus;
            if (dtCommon2[i].isApproved == System.DBNull.Value)
            {

The isApproved returns null true or false... but nothing I try seems to work to compare if it's null, it wont build.

Error 1 Operator '==' cannot be applied to operands of type 'bool' and 'System.DBNull'

Upvotes: 0

Views: 706

Answers (3)

Anuraj
Anuraj

Reputation: 19598

You are getting this error because we cannot assign Null to bool. Either you need to make IsApproved as Nullable boolean, can be achieved by declaring like bool? IsApproved. Or you need to check like dt[i] != null.

UPDATE: Try this Convert.IsDBNull(object) check whether is null or not. You can also use Convert.ToBoolean(object). It will return false, if the object is null.

Upvotes: 1

rgargente
rgargente

Reputation: 1840

The error clearly states isApproved is a bool type, not bool? or anything else. If this is the case, I suggest you to review the logic of the program. Maybe you must declare it as bool? on ArtworkMyAvailableVotesDataTable, but I'm not sure that's an option.

Upvotes: 1

Shadow Wizard
Shadow Wizard

Reputation: 66388

Looks like isApproved is ordinary boolean.. anyway if it's bool? you can play it safe with such code:

if (dtCommon2[i].isApproved == null || !dtCommon2[i].isApproved.Value)

Edit: You're not using ordinary DataTable where the raw value can be indeed DBNull.. I guess the component you're using is dealing with this already and present you with "ready to use" class of data. So if isApproved is boolean it will already be false when the field will be empty.

Upvotes: 2

Related Questions