C# 复选框数据绑定默认值为空
我正在将复选框数据绑定到bindingsource,如果我不单击该复选框,它将向我的数据库返回空值 这是数据绑定代码:C# 复选框数据绑定默认值为空,c#,.net,winforms,checkbox,data-binding,C#,.net,Winforms,Checkbox,Data Binding,我正在将复选框数据绑定到bindingsource,如果我不单击该复选框,它将向我的数据库返回空值 这是数据绑定代码: checkGehuwd.DataBindings.Add("Checked", PersonenBindingSource, "gehuwd", true, DataSourceUpdateMode.OnPropertyChanged); 如何返回默认值false 您可以通过以下方式将数据绑定到属性: checkBox1.DataBindings.A
checkGehuwd.DataBindings.Add("Checked", PersonenBindingSource, "gehuwd", true,
DataSourceUpdateMode.OnPropertyChanged);
如何返回默认值false
您可以通过以下方式将数据绑定到属性:
checkBox1.DataBindings.Add("CheckState", bs, "DataFieldName", true,
DataSourceUpdateMode.OnPropertyChanged, CheckState.Indeterminate);
这样,当数据源中field的值为null时,UI中将显示CheckState.Undeterminate
注意
dt = new DataTable();
var c1 = dt.Columns.Add("C1", typeof(int));
c1.AllowDBNull = true;
//Uncomment the next statement if you want default value be 0 = unchecked
//c1.DefaultValue = 0;
//Uncomment the next statement if you want to allow the user to set value to null
//checkBox1.ThreeState = true;
var bs = new BindingSource();
bs.DataSource = dt;
checkBox1.DataBindings.Add("CheckState", bs, "C1", true,
DataSourceUpdateMode.OnPropertyChanged, CheckState.Indeterminate);
this.bindingNavigator1.BindingSource = bs;
- 如果希望列的默认值为
或未选中,则将0
的DataColumn
设置为DefaultValue
0
- 如果您想让用户也将字段的值设置为null,那么将
复选框的属性设置为true就足够了
dt = new DataTable();
var c1 = dt.Columns.Add("C1", typeof(int));
c1.AllowDBNull = true;
//Uncomment the next statement if you want default value be 0 = unchecked
//c1.DefaultValue = 0;
//Uncomment the next statement if you want to allow the user to set value to null
//checkBox1.ThreeState = true;
var bs = new BindingSource();
bs.DataSource = dt;
checkBox1.DataBindings.Add("CheckState", bs, "C1", true,
DataSourceUpdateMode.OnPropertyChanged, CheckState.Indeterminate);
this.bindingNavigator1.BindingSource = bs;
为什么不在db处设置默认值false?我尝试过它仍然将其设置为null。它是可为null的布尔值吗?它是sqlite数据库中的一个整数值,链接到数据集,链接到bindingsource,将数据绑定到复选框。我也不认为最好将非布尔值绑定到复选框,但不管怎样都可以。当我不单击复选框时,这仍然会插入空值,即使在设置CheckState.true为默认值时,当您单击复选标记并使复选框显示复选标记时,它将插入1。单击并取消选中时插入0。单击时插入null,并将复选框设置为“不确定”,复选框中显示正方形。要测试它,只需使用我在示例中提供的代码。这样的代码可以简单地测试,而不需要任何数据库。请确保您阅读了示例中的注释部分和注释。这篇文章似乎回答了您的问题,如果您对答案有任何疑问,或者您觉得它有用,请告诉我:)