将 DataGridViewComboBox 列添加并填充到绑定的 Datagridview

Adding and Populating DataGridViewComboBoxcolumn to Bound Datagridview

我正在尝试允许 DataGridView 允许用户编辑字段(为简单起见,假设它只是项目,每个项目都可以有一个条件,允许的值取自第二个 table [条件]

例如

数据结构(简化)

项目Table

条件Table

所需的网格外观:

我的网格应该如下所示:

Item #   Qty   Condition
123456   10    [ New  v]   <-- A drop-down
234567   55    [ Used v]   
345678   99    [ New  v]   
etc.

战略:

我正在尝试通过以下方式进行设置:

  1. 将grid绑定到第一个Items table(抓取前三个 包含项目每一行的实际值的列 table)

  2. 创建新的 DataGridViewComboBoxColumn ("CondCombo") 并绑定 从条件 table 到它的所有允许项目,

  3. 遍历网格并为每个网格设置 CondCombo 的值 行到条件行的值

  4. 隐藏条件(文本)列。

问题:

我能够添加列并加载条件值,但我完全无法设置所选值以匹配项目中的条件 table;此外,当我选择或单击另一个单元格时,我在组合中所做的任何选择都会被清空。

这是我目前得到的代码:任何帮助都将不胜感激!

Sub SetupGrid(byref myGrid as DataGridView, 
              myConn as sqlite.sqliteConnection)

    Dim myAdapter As System.Data.SQLite.SQLiteDataAdapter

    myGrid.VirtualMode = true
    myAdapter = new system.data.sqlite.sqliteadapter(_
        "Select ID, ItemNum, Qty, Condition FROM Items", myConn)
    myAdapter.SelectCommand.CommandType = CommandType.Text

    ' Fill the main grid with the item data
    dim ds as new DataSet
    myAdapter.Fill(ds)
    myGrid.DataSource = ds.Tables(0)

    ' Now create and load the ComboBox column
    dim cboColumn as new DataGridViewComboBoxColumn
    With cboColumn
        .DataPropertyName = "ConditionAbbrev"
        .name = "CondCombo"
        .HeaderText = "Cond"

        ' Bind the ComboColumn
        Dim conditionsAdapter As System.Data.SQLite.SQLiteDataAdapter
        Dim condTable As DataTable
        using cmd as new Sqlite.sqliteCommand(_
            "SELECT ConditionAbbrev FROM Conditions", myconn)
            conditionsAdapter.selectCommand = cmd
            conditionsApapter.fill(condTable)
         end using

         .DataSource = condTable
         .DataPropertyName = "ConditionAbbrev"
         .ValueMember = "ConditionAbbrev"
         .DisplayMember = .ValueMember
      end with

      ' Set the selected combo member to be the same as the Condition (text) field value:

      for each curRow as dataGridViewrow in myGrid.Rows()
          curRow.cells("CondCombo").value = _
              curRow.Cells("Condition").value
      next

      ' Hide the Condition (text) field)
      myGrid.Columns("Condition").visible = false

      ' Hide the ID field
      myGrid.Columns("ID").visible = false
end sub

DataPropertyName 的设置不正确。您将一个列表绑定到网格,将一个列表绑定到列。 DisplayMemberValueMember 是绑定到该列的项目的 columns/properties 的名称。 DataPropertyName 是绑定到网格的 column/property 项的名称。在您的情况下,在我看来 DataPropertyName 应该设置为 "Condition".