如何按列名设置DataGridViewRow的单元格值? [英] How to set Cell value of DataGridViewRow by column name?

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

问题描述

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

但是,我想按列名添加单元格值而不是按索引添加,如下所示:

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的单元格值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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