How to set Cell value of DataGridViewRow by column name?

筅森魡賤 提交于 2019-11-29 03:31:24

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;

I tried it too and got the same result. This is a little verbose, but it works:

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

When you use the ColumnName indexer of the DataGridViewCellCollection, internally it tries to get the column index using the ColumnName from the owning/parent DataGridView of this DataGridViewRow instance. In your case the row hasn't been added to the DataGridView and hence the owning DataGridView is null. That's why you get the error that It couldn't find the column named code.

IMO the best approach (same as Derek's) would be to the add the row in the DataGridView and use the returned index to the get the row instance from the grid and then use the column name to access the cells.

The problem is that referencing cells by name doesn't work until the row is added to the DataGridView. Internally it uses the DataGridViewRow.DataGridView property to get at the column names, but that property is null until the row is added.

Using C#7.0's local function feature, the code can be made halfway readable.

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

Another alternative:
Suppose the name of your DataGridView is dataGridView1.

var row = new DataGridViewRow();
// Initialize Cells for this row
row.CreateCells(_dataGridViewLotSelection);

// Set values
row.Cells[dataGridView1.Columns.IndexOf(code)].Value = product.Id;
row.Cells[dataGridView1.Columns.IndexOf(description)].Value = product.Description;
// Add this row to DataGridView
dataGridView1.Rows.Add(row);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!