How to set Cell value of DataGridViewRow by column name?

后端 未结 5 737
小蘑菇
小蘑菇 2020-12-15 20:51

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

Data         


        
5条回答
  •  不思量自难忘°
    2020-12-15 21:08

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

提交回复
热议问题