如何通过列名设置DataGridViewRow的单元格值?

19
在Windows Forms中,我正试图通过将DataGridViewRows插入其中来手动填充DataGridView,因此我的代码看起来像这样:
DataGridViewRow row = new DataGridViewRow();
row.CreateCells(dgvArticles);
row.Cells[0].Value = product.Id;
row.Cells[1].Value = product.Description;
.
.
.
dgvArticles.Rows.Add(row);

然而,我希望通过列名而不是索引来添加单元格的值,就像这样:

row.Cells["code"].Value = product.Id;
row.Cells["description"].Value = product.Description;

但是像这样做会出现一个错误,说它找不到名为“code”的列。 我正在从设计器中设置DataGridView的列,像这样: Columns from DataGridViewDesigner

我做错了什么吗?我该如何完成我想做的事情?

5个回答

25
为了实现您想要的方法,需要按照以下方式进行:
//Create the new row first and get the index of the new row
int rowIndex = this.dataGridView1.Rows.Add();

//Obtain a reference to the newly created DataGridViewRow 
var row = this.dataGridView1.Rows[rowIndex];

//Now this won't fail since the row and columns exist 
row.Cells["code"].Value = product.Id;
row.Cells["description"].Value = product.Description;

应将 row.Cells["code"].Value 修改为 row.Cells["Code"].Value,首字母大写。或者 row.Cells[code.Name].Value,首字母小写。 - Bravo Yeung
1
根据OP提供的屏幕截图,@BravoYeung表示:Name属性设置为小写的"code",而HeaderText属性设置为大写的"Code"。在这种情况下,您需要通过索引器引用列Name而不是HeaderText - Derek W

4

我也尝试过,得到了同样的结果。这可能有点啰嗦,但它确实有效:

row.Cells[dataGridView1.Columns["code"].Index].Value = product.Id;

行.Cells["code"].Value 应该修改为 行.Cells["Code"].Value,首字母大写。或者行.Cells[code.Name].Value,首字母小写。 - Bravo Yeung

3
当您使用 DataGridViewCellCollection 的 ColumnName 索引器时,它会尝试从拥有/父级 DataGridView 中使用 ColumnName 获取列索引。在您的情况下,该行尚未添加到 DataGridView 中,因此拥有 DataGridView 为空。这就是为什么会出现“找不到名为 code 的列”的错误。
我认为最好的方法(与 Derek 的方法相同)是将行添加到 DataGridView 中,并使用返回的索引从网格中获取行实例,然后使用列名称访问单元格。

0
问题在于,在将行添加到 DataGridView之前,通过名称引用单元格无法正常工作。内部使用 DataGridViewRow.DataGridView 属性来获取列名称,但是在添加行之前该属性为 null。
使用 C#7.0 的本地函数特性,可以使代码变得半易读。
DataGridViewRow row = new DataGridViewRow();
row.CreateCells(dgvArticles);

DataGridViewCell CellByName(string columnName)
{
    var column = dgvArticles.Columns[columnName];
    if (column == null)
        throw new InvalidOperationException("Unknown column name: " + columnName);
    return row.Cells[column.Index];
}


CellByName("code").Value = product.Id;
CellByName("description").Value = product.Description;
.
.
.
dgvArticles.Rows.Add(row);

0
另一种选择:
假设你的DataGridView的名称是dataGridView1
var row = new DataGridViewRow();
// Initialize Cells for this row
row.CreateCells(_dataGridViewLotSelection);

// Set values
row.Cells[dataGridView1.Columns.IndexOf(code)].Value = product.Id;
row.Cells[dataGridView1.Columns.IndexOf(description)].Value = product.Description;
// Add this row to DataGridView
dataGridView1.Rows.Add(row);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接