I am databinding a checkbox to a bindingsource, if i dont click the checkbox it will return a null value to my database.
This is the databinding code:
checkGehuwd.DataBindings.Add("Checked", PersonenBindingSource, "gehuwd", true,
DataSourceUpdateMode.OnPropertyChanged);
how do i return a default value of false?
Greetings Andy
You can use data-binding to CheckState
property this way:
checkBox1.DataBindings.Add("CheckState", bs, "DataFieldName", true,
DataSourceUpdateMode.OnPropertyChanged, CheckState.Indeterminate);
This way, when the value of filed in the data source is null, CheckState.Indeterminate
will be shown in UI.
Note
If you want the default value of column be 0
or unchecked, then set the DefaultValue
of DataColumn
to 0
.
If you want to let the user also set value of the field to null, it's enough to set ThreeState
property of CheckBox
to true.
Example
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;