【问题标题】:How to populate DataGridView with textbox and combobox with comboboxcells having different value lists如何使用具有不同值列表的组合框单元填充文本框和组合框的 DataGridView
【发布时间】:2012-07-16 07:00:03
【问题描述】:

我有三列,按顺序排列,文本框、组合框和文本框:

this.columnLocalName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.columnLocalAddress = new System.Windows.Forms.DataGridViewComboBoxColumn();
this.columnLocalPort = new System.Windows.Forms.DataGridViewTextBoxColumn();   

它们又在一个 datagridview 中,如下所示:

this.dataGridViewLocalProfile.Columns.AddRange(
new System.Windows.Forms.DataGridViewColumn[] {
                    this.columnLocalName,
                    this.columnLocalAddress,
                    this.columnLocalPort});

稍后我将尝试为每个组合框单元格添加不同的值,如下所示:

foreach (profile in localProfile.List)
{
DataGridViewComboBoxCell cell =(DataGridViewComboBoxCell)
(dataGridViewLocalProfile.Rows[dataGridViewLocalProfile.Rows.Count - 1].
Cells["columnLocalAddress"]);

cell.Items.Clear();
cell.Items.Add(profile.Address.ToString());

dataGridViewLocalProfile.Rows.Add(
new string[] { profile.Name, profile.Address, profile.Port });
}

这会产生一个数据网格,其中填充了第一列和最后一列,并且组合框列为空。带有我处理的数据错误。消息是:

DataGridViewComboBoxCell value is not valid.

我已经阅读了大部分帖子,但找不到解决方案。

我尝试过像这样设置数据源:

cell.DataSource = new string[] { profile.Address };

仍然得到空的组合框列并显示数据错误

DataGridViewComboBoxCell value is not valid.

我认为这非常棘手,因为我为每个组合框单元添加了不同的值。

任何人都可以帮助我了解如何使这项工作。

/最佳

【问题讨论】:

    标签: c# datagridview datagridviewcolumn datagridviewcombobox datagridviewcomboboxcell


    【解决方案1】:

    游戏迟到了,但无论如何,这就是解决方案。

    问题出在foreach 循环中。最后一个现有行中的ComboBox 单元格填充了一个项目。但是随后,使用当前的profile 对象添加了一个全新的行:

    dataGridViewLocalProfile.Rows.Add( new string[] { profile.Name, profile.Address, profile.Port });
    

    此新行中ComboBox 单元格的项目为空,因此profile.Address 无效。将foreach 循环更改为如下所示,您就是金子:

    foreach (Profile p in this.localProfile)
    {
      DataGridViewRow row = new DataGridViewRow();
      row.CreateCells(this.dataGridView1);
    
      DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)row.Cells[1];
      cell.Items.Clear();
      cell.Items.Add(p.Address);
    
      row.Cells[0].Value = p.Name;
      row.Cells[1].Value = p.Address;
      row.Cells[2].Value = p.Port;
      this.dataGridView1.Rows.Add(row);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-26
      相关资源
      最近更新 更多