简体   繁体   中英

how to convert the bool to nullable bool (bool?)

i have a table provider with column

                 implied(tiny int)(something like nullable bool)
                 providerid(int)

I have a form and i have check box

I am doing winforms applications using c# ..

i am using enitities and my dbcontext name is dbcontext

How to covert bool to nullable bool(bool?) in C sharp.

I have tried this way

      if (chkbox.checked == true)

            bool yes = 0;
        else

          bool   yes = 1;

        dbcontext.implied = yes;

but got an error

Cannot convert bool to bool?

Explicitly cast to a bool?

bool b = true;
bool? b2 = (bool?)b;

In case it's of interest, you can convert bool? to bool . You can do this by first checking HasValue which will return false if it's null or true if it is not null.

If it does have a value, you can cast to a bool.

bool? b = null;
if (b.HasValue == false) // it's null
{
  //initialize b 
  b = false;
}
else if((bool)b == true)
{
  // do whatever
}

Check out http://msdn.microsoft.com/en-us/library/bb384091.aspx for bool? to bool conversion.

Can directly do something like

bool result = true;
bool? toBindData = (bool?)result;

dbcontext.implied = new Nullable<bool>(yes);

Try Convert.ToBoolean(Your checkBox)

Below how I tested on my DataGridView to check CheckBox column and it works fine.

if ( Convert.ToBoolean( dgv.Rows[r].Cells["Delete"].Value))
{
    //Do work;
}

Here is a fix:

if (Convert.ToBoolean(chkbox.checked) == true)

Or a simpler version:

if (Convert.ToBoolean(chkbox.checked))

as the default condition anticipates the Truth of the statement.

Dependencies:

using.System;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM