我在我的DataGridView中添加ComboBoxColumn
,并使用BindingSources将其链接到单独的相关Department表。
新行显示第一个列出的部门(帐户),但默认情况下不会选择它,从而导致错误:
无法将值NULL插入列' DeptID',表中 ' StaffDB.dbo.Staff&#39 ;;列不允许空值。 INSERT失败。
根据回答here at SO的建议,我使用以下方法设置默认值:
comboCol.DefaultCellStyle.NullValue = _bsDept(0)("Department")
comboCol.DefaultCellStyle.DataSourceNullValue = _bsDept(0)("DeptID")
这似乎适用于调试,值为4和" Accounts",但仍会产生相同的错误。
以下是ComboBox的所有相关设置:
Dim comboCol = New DataGridViewComboBoxColumn()
comboCol.DataSource = _bsDept
comboCol.ValueMember = "DeptID"
comboCol.DisplayMember = "Department"
'staff table..
comboCol.DataPropertyName = "DeptID"
comboCol.HeaderText = "Department"
comboCol.DefaultCellStyle.Format = "d"
'the first Department "Accounts" appears to be selected, but it isn't
comboCol.DefaultCellStyle.NullValue = _bsDept(0)("Department")
comboCol.DefaultCellStyle.DataSourceNullValue = _bsDept(0)("DeptID")
dgvStaff.Columns.Add(comboCol)
为什么忽略我的默认值? (如果我自己选择部门,ComboBox会起作用。)
答案 0 :(得分:1)
我不确定那些DefaultCellStyle道具是否比控制如何显示Null等更多,给定名称。有DefaultValuesNeeded
事件可能是设置默认值的更合适的位置。例如(有些代码我很方便):
Private Sub dgv2_DefaultValuesNeeded(sender As Object,
e As DataGridViewRowEventArgs) Handles dgv2.DefaultValuesNeeded
'defaults
e.Row.Cells("Fish").Value = "Cod"
e.Row.Cells("Bird").Value = "Raven"
e.Row.Cells("itemDate").Value = DateTime.Now.Date
End Sub
在您的情况下,您将从部门来源提供一个值。