In windows forms, I\'m trying to fill a DataGridView
manually by inserting DataGridViewRows
to it, so my code looks like this:
Data
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.
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);
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);
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;