如何按列名设置DataGridViewRow的Cell值?

在Windows窗体中,我试图通过插入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); 

但是,我想按列名添加Cell值,而不是通过索引来添加它,如下所示:

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

但这样做会抛出一个错误,说它无法找到名为“code”的列。 我正在设计设计器中的DataGridView列,如下所示: DataGridViewDesigner中的列

难道我做错了什么? 我怎样才能完成我想做的事情?

因此,为了实现您希望的方法,需要以这种方式完成:

 //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; 

当您使用DataGridViewCellCollection的ColumnName索引器时,它在内部尝试使用此DataGridViewRow实例的拥有/父DataGridView中的ColumnName来获取列索引。 在您的情况下,该行尚未添加到DataGridView,因此拥有的DataGridView为null。 这就是为什么你得到错误, 它无法找到名为code的列。

IMO最好的方法(与Derek相同)是在DataGridView添加行并使用返回的索引从网格中获取行实例,然后使用列名访问单元格。

我也试过了,得到了同样的结果。 这有点冗长,但它有效:

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

问题是,在将行添加到DataGridView之前,按名称引用单元格不起作用。 在内部,它使用DataGridViewRow.DataGridView属性来获取列名,但在添加行之前该属性为null。

使用C#7.0的本地函数function,代码可以在中途读取。

 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);