更新现有的 DataGridViewComboBoxColumn Items 集合

问题描述 投票:0回答:2

我们有

DataGridViewComboBoxColumn
,其中有四个固定值。在运行时,当事件
dataGridView1_EditingControlShowing
发生时,我们尝试将新项目追加到
DataGridViewComboBoxColumn

private void dataGridView1_EditingControlShowing(object sender, 
                                             DataGridViewEditingControlShowingEventArgs e)
{
   ComboBox combo = e.Control as ComboBox;
   if (combo != null)
   {
      combo.DropDown += new System.EventHandler(ComboBox1_DropDown);
   }
}

private void ComboBox1_DropDown(object sender, System.EventArgs e)
{
   ComboBox comboBox = (ComboBox)sender;
   if (comboBox.Items != null)
   {
      List<String> elementname = Elements();
      foreach (string s in elementname)
      {
         if (!comboBox.Items.Contains(s))
         {
            comboBox.Items.Add(s);
         }
      }
   }
}

我遇到了这个异常:

您能否建议如何将值添加到

DataGridViewComboBoxColumn
集合中现有的
Items
中。

c# datagridview datagridviewcolumn
2个回答
1
投票

您将添加到编辑控件的

Items
中,而不是添加到
Items
ComboBoxColumn
中,最终将用于验证。

为了轻松访问托管 DGV,我们使用特殊类型

DataGridViewComboBoxEditingControl
。 现在,我们将在
Items
事件中将新选择添加到两个
ComboBox1_DropDown
集合中::

DataGridViewComboBoxEditingControl comboBox = (DataGridViewComboBoxEditingControl)sender;
DataGridView dgv = comboBox.EditingControlDataGridView; 
if (comboBox.Items != null && dgv != null)
{
    DataGridViewComboBoxColumn dcbc =
        (DataGridViewComboBoxColumn) dgv.Columns[dgv .CurrentCell.ColumnIndex];

    List<String> elementname = Elements.ToList();
    foreach (string s in elementname)
    {
        if (!comboBox.Items.Contains(s))
        {
          comboBox.Items.Add(s);
          dcbc.Items.Add(s);
        }
    }
}

新的

Items
不会是persistet,除非你为其编写代码。

因此,如果您已将字段设置为新值并保存它们,则还必须在重新加载 DGV 之前保存并重新加载这些新值,否则这些值将不会出现在

Column
的值列表中并抛出
DataError

通常存储它们的位置是 DBMS 中的

DataTable
,但也可以使用任何其他外部存储,例如
XML
文件或可能是 动态资源 等。但在我看来,DBMS 是最自然的选择。


0
投票

我知道这是一个非常古老的线程,但无论如何我都会发布我的解决方案。它可以帮助别人。 此示例将仅更新一个单元格 (DataGridViewComboBoxCell)

int rowIndex = dbGrid.CurrentCell.RowIndex;
string test = dbGrid.CurrentCell.Value.ToString();
List<string> itemList = new List<string>{"one","two","three"};

DataGridViewComboBoxCell cbbCell = new DataGridViewComboBoxCell();

cbbCell.Items.Clear();
foreach (var item in itemList)
{
    cbbCell.Items.Add(item);
}
dbGrid["Column", rowIndex] = cbbCell;
© www.soinside.com 2019 - 2024. All rights reserved.