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

16 c# datagridview winforms datagridviewrow

在Windows窗体中,我试图DataGridView通过插入DataGridViewRows来手动填充,所以我的代码如下所示:

DataGridViewRow row = new DataGridViewRow();
row.CreateCells(dgvArticles);
row.Cells[0].Value = product.Id;
row.Cells[1].Value = product.Description;
.
.
.
dgvArticles.Rows.Add(row);
Run Code Online (Sandbox Code Playgroud)

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

row.Cells["code"].Value = product.Id;
row.Cells["description"].Value = product.Description;
Run Code Online (Sandbox Code Playgroud)

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

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

Der*_*k W 18

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

//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;
Run Code Online (Sandbox Code Playgroud)