Andy G Andy G - 10 months ago 81 Question

DGV combobox displays, but does not choose, default value

I'm adding a

to my DataGridView and, with BindingSources, linking it to a separate related Department table.

A new row displays the first listed department (Accounts), but it doesn't select it by default, causing the error:

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

Following advice from an answer here at SO, I'm using the following to set the defaults:

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

This appears to work on debugging, with the values 4 and "Accounts", but still yields the same error.

Here are all the relevant settings for the 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")


Why are my default values being ignored?
(The ComboBox works if I choose a Department myself.)


I am not sure those DefaultCellStyle props do more than control how Nulls etc are displayed, given the name. There is a DefaultValuesNeeded event which might be a more appropriate place to set default values. For instance (some code I have handy that does just that):

Private Sub dgv2_DefaultValuesNeeded(sender As Object, 
              e As DataGridViewRowEventArgs) Handles dgv2.DefaultValuesNeeded
    e.Row.Cells("Fish").Value = "Cod"
    e.Row.Cells("Bird").Value = "Raven"
    e.Row.Cells("itemDate").Value = DateTime.Now.Date
End Sub

In your case, you would supply a value from the Department source.