2016-04-30 54 views
2

我将一个ComboBoxColumn添加到我的DataGridView,并与BindingSources一起将其链接到单独的相关部门表。DGV组合框显示但不选择默认值

一个新行显示的第一家上市的部门(账户),但它默认情况下不选择它,会导致错误:

Cannot insert the value NULL into column 'DeptID', table 'StaffDB.dbo.Staff'; column does not allow nulls. INSERT fails.

在从一个答案here at SO建议,我使用以下设置默认设置:

comboCol.DefaultCellStyle.NullValue = _bsDept(0)("Department") 
    comboCol.DefaultCellStyle.DataSourceNullValue = _bsDept(0)("DeptID") 

这似乎适用于调试,值为4和“帐户”,但仍然会产生相同的错误。

这里是所有的组合框的相关设置:

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) 

为什么我的默认值被忽略? (组合框如果我自己选择一个部门的作品)。

+1

我不确定这些'DefaultCellStyle'道具的作用不仅仅在于控制如何显示空值等。有一个'DefaultValuesNeeded'事件可能更合适 – Plutonix

+0

谢谢,这是有道理的;)。如果您将它添加为答案,我可以接受它,使用此代码'e.Row.Cells(“Department”)。Value = _bsDept(0)(“DeptID”)'在事件中。 –

回答

1

我不确定那些DefaultCellStyle道具的作用超过了控制如何显示空值等名称。有一个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 

在你的情况,你会从部门来源提供一个值。

+0

这解决了这个问题,谢谢。对于这个属性的命名没有帮助,因为这个异常指定了一个空值,并且这些属性是用于'默认空值'的,但是你去了;) –

+0

我更典型的将新行添加到数据源... this当'AllowUserToAddRows' = true时更适合。 – Plutonix