2

I'm adding a ComboBoxColumn 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")

    dgvStaff.Columns.Add(comboCol)

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

Community
  • 1
  • 1
Andy G
  • 19,232
  • 5
  • 47
  • 69
  • 1
    I am not sure those `DefaultCellStyle` props do more than control how Nulls etc are displayed. There is a `DefaultValuesNeeded` event which might be more appropriate – Ňɏssa Pøngjǣrdenlarp Apr 30 '16 at 18:33
  • Thank you, that makes some sense ;). If you add it as an answer I can accept it, using this code `e.Row.Cells("Department").Value = _bsDept(0)("DeptID")` in the event. – Andy G Apr 30 '16 at 18:40

1 Answers1

1

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
    'defaults
    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.

Ňɏssa Pøngjǣrdenlarp
  • 38,411
  • 12
  • 59
  • 178
  • This solved the problem, thank you. The naming of the properties doesn't help, given that the exception specifies a null value, and the properties are for 'default nulls', but there you go ;) – Andy G Apr 30 '16 at 18:49
  • I more typically add the new row to the datasource...this is more for when `AllowUserToAddRows` = true. – Ňɏssa Pøngjǣrdenlarp Apr 30 '16 at 18:51