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.
dbcontext.implied = new Nullable<bool>(yes);
Can directly do something like
bool result = true;
bool? toBindData = (bool?)result;
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;
加载中,请稍侯......
精彩评论