c# - 如何使用具有不同值列表的组合框单元格的文本框和组合框填充 DataGridView

标签 c# datagridview datagridviewcolumn datagridviewcombobox datagridviewcomboboxcell

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

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

它们依次位于数据 GridView 中,如下所示:

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.

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

任何人都可以帮助我如何完成这项工作。

/最佳

最佳答案

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

问题出在 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);
}

关于c# - 如何使用具有不同值列表的组合框单元格的文本框和组合框填充 DataGridView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11521097/

相关文章:

c# - 泛型、枚举和自定义属性——这可能吗?

c# - 如何获取具有给定属性的属性列表?

vb.net - 如何检测特定 datagridview 列的单元格值更改? - VB.NET

c# - 我可以将哪些命令行构建工具(如 make)与 Mono C# 一起使用?

c# - 如何在c#中自定义颜色?

c# - 鼠标倾斜水平滚动在 DataGridView 中不起作用

c# - 是否可以从 listview 获取值并将其转发到 Windows 窗体中的 DataGridView?

c# - 如何在数据绑定(bind)时以编程方式向 datagridview 添加一行?

c# - 有没有一种快速的方法可以将 DataGridView 的所有列设置为不可见?

c# - 同一列中包含多个信息的 DataGridview