Search code examples
c#winformsdatagridviewdatagridviewrow

How to set Cell value of DataGridViewRow by column name?


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;

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: Columns from DataGridViewDesigner

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


Solution

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