【问题标题】:DGV combobox displays, but does not choose, default valueDGV 组合框显示但不选择默认值
【发布时间】:2016-05-01 02:43:23
【问题描述】:

我正在向我的 DataGridView 添加ComboBoxColumn,并使用 BindingSources 将其链接到单独的相关部门表。

新行显示第一个列出的部门(Accounts),但默认不选中,导致错误:

无法将值 NULL 插入列“DeptID”,表 'StaffDB.dbo.Staff';列不允许空值。插入失败。

根据答案 here at SO 的建议,我使用以下设置默认值:

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

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

以下是 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)

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

【问题讨论】:

  • 我不确定那些 DefaultCellStyle 道具是否能控制 Null 等的显示方式。有一个DefaultValuesNeeded 事件可能更合适
  • 谢谢,这有点道理;)。如果您将其添加为答案,我可以接受,请在活动中使用此代码 e.Row.Cells("Department").Value = _bsDept(0)("DeptID")

标签: vb.net winforms datagridview


【解决方案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

在您的情况下,您将提供来自 Department 源的值。

【讨论】:

  • 这解决了问题,谢谢。属性的命名没有帮助,因为异常指定了一个空值,并且属性是“默认空值”,但是你去;)
  • 我通常将新行添加到数据源中......这更适用于 AllowUserToAddRows = true 时。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-08
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
  • 2019-01-20
  • 2019-04-16
  • 1970-01-01
相关资源
最近更新 更多