我按顺序排列了三列,文本框、组合框和文本框:
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/