I have a DataGridView
:
dgvPersonnelInfo.DataSource = personnelInfo;
Now I add a column as follows:
var arabicYear = new DataGridViewColumn();
arabicYear.Name = "arabicYear";
arabicYear.HeaderText = "Arabic Year";
arabicYear.CellTemplate = new DataGridViewTextBoxCell();
dgvPersonnelInfo.Columns.Insert(4, arabicYear);
Then I want to assign the value of this cell as follows:
for (int i = 0; i < dgvPersonnelInfo.Rows.Count; i++)
{
dgvPersonnelInfo.Rows[i].Cells[4].Value = arabicDeathYearMonth;
}
It does not work, the cell is empty. How can I assign the cell values?
I assume you are performing the above code in the
Form
constructor; that was the only way I could replicate your empty column.Form.Load
. This should solve the main issue.Arabic Year
, is not being populated but instead column 3 has the intended data.Even though your code:
inserts the column into the 4th index (which will correctly display it), future access of the column will be through the 0th index. To verify this is true, hook up the following handler:
By clicking cells in each column you'll see that the
Arabic Year
column looks like column 4, but is actually column 0. Why? Inserted columns are indexed before the bound columns of yourDataSource
due to the way binding is resolved after the constructor finishes andDataBindingComplete
is called in the background.You could fix this by changing your assignments to this column as:
but because of the inherent ambiguity of the index assignment I just explained, you would be better off doing the following instead: