2016-04-30 90 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