复选框数据绑定默认值为null

And*_*els 3 .net c# data-binding checkbox winforms

我正在将一个复选框数据绑定到一个bindingsource,如果我没有单击该复选框,它将返回一个空值到我的数据库.

这是数据绑定代码:

 checkGehuwd.DataBindings.Add("Checked", PersonenBindingSource, "gehuwd", true,
            DataSourceUpdateMode.OnPropertyChanged);
Run Code Online (Sandbox Code Playgroud)

我如何返回默认值false?

问候安迪

Rez*_*aei 5

您可以这样使用数据绑定到CheckState属性:

checkBox1.DataBindings.Add("CheckState", bs, "DataFieldName", true,
    DataSourceUpdateMode.OnPropertyChanged, CheckState.Indeterminate);
Run Code Online (Sandbox Code Playgroud)

这样,当数据源中的字段值为null时,CheckState.Indeterminate将在UI中显示.

注意

  • 如果你想列的默认值0或取消选中,然后设定DefaultValueDataColumn0.

  • 如果您想让用户也将字段的值设置为null,则将ThreeState属性设置CheckBox为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;
Run Code Online (Sandbox Code Playgroud)