2016-09-30 147 views
2

我數據綁定一個複選框到的BindingSource,如果我不點擊複選框,將一個空值返回到我的數據庫。複選框綁定默認值爲空

這就是綁定代碼:

checkGehuwd.DataBindings.Add("Checked", PersonenBindingSource, "gehuwd", true, 
      DataSourceUpdateMode.OnPropertyChanged); 

我如何返回的默認值爲false?

問候安迪

+0

爲什麼不設置默認值在DB假的? – Berkay

+0

我試過它仍然將它設置爲null。 –

+1

是'gehund'可空的布爾? – Crowcoder

回答

1

您可以使用數據綁定這種方式CheckState屬性:

checkBox1.DataBindings.Add("CheckState", bs, "DataFieldName", true, 
    DataSourceUpdateMode.OnPropertyChanged, CheckState.Indeterminate); 

這樣,當在數據源提交的值爲空,CheckState.Indeterminate將在UI中顯示。

注意

  • 如果你想列的默認值是0或取消選中,然後設置的DataColumnDefaultValue0

  • 如果您想讓用戶也將該字段的值設置爲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; 
+0

這仍然會插入空當,我不點擊它,設置CheckState.true即使默認 –

+0

它會插入1當你點擊選中標記,使該複選框顯示選中標記。當您點擊並取消選中時,插入0。單擊時將插入爲空,並將複選框設置爲不確定,從而在複選框中顯示正方形。 –

+0

要測試它,只需使用我在示例中提供的代碼。這樣的代碼可以簡單地進行測試而不需要任何數據庫。 –