gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 07:44:18 24 4
gpt4 key购买 nike

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

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

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

但是这样做会抛出一个错误,提示找不到名为“代码”的列。我正在这样设置设计器中的 DataGridView 列: Columns from 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;

关于c# - 如何通过列名设置 DataGridViewRow 的单元格值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22123368/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com