如何通过列名设置DataGridViewRow的Cell值? [英] How to set Cell value of DataGridViewRow by column name?

查看:757
本文介绍了如何通过列名设置DataGridViewRow的Cell值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In windows forms, I'm trying to fill a DataGridView manually by inserting DataGridViewRows to it, so my code looks like this:

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

但是,我想按列名添加Cell值,而不是按索引来添加,就像这样:

However, I would like to add the Cell value by column name instead of doing it by the index, something like this:

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

但是这样做会引发错误,提示它找不到名为"code"的列. 我正在像这样从设计器设置DataGridView列:

But doing it like that throws an error saying it couldn't find the column named "code". I'm setting the DataGridView columns from the designer like this:

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

Am I doing something wrong? How can I accomplish what I want to do?

推荐答案

因此,为了完成您所希望的方法,需要采用以下方式:

So in order to accomplish the approach you desire it would need to be done this way:

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

这篇关于如何通过列名设置DataGridViewRow的Cell值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆