Insert column with different values after binding DataGridView

92 views Asked by At

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?

1

There are 1 answers

0
OhBeWise On BEST ANSWER
for (int i = 0; i < dgvPersonnelInfo.Rows.Count; i++)
{
    dgvPersonnelInfo.Rows[i].Cells[4].Value = arabicDeathYearMonth;
}

I assume you are performing the above code in the Form constructor; that was the only way I could replicate your empty column.

  1. Move this code somewhere else, say Form.Load. This should solve the main issue.
  2. You'll now notice that column 4, Arabic Year, is not being populated but instead column 3 has the intended data.

Even though your code:

dgvPersonnelInfo.Columns.Insert(4, arabicYear);

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:

private void dgvPersonnelInfo_CellClick(object sender, DataGridViewCellEventArgs e)
{
    dgvPersonnelInfo.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = e.ColumnIndex;
}

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 your DataSource due to the way binding is resolved after the constructor finishes and DataBindingComplete is called in the background.

You could fix this by changing your assignments to this column as:

dgvPersonnelInfo.Rows[i].Cells[0].Value = arabicDeathYearMonth;

but because of the inherent ambiguity of the index assignment I just explained, you would be better off doing the following instead:

dgvPersonnelInfo.Rows[i].Cells["arabicYear"].Value = arabicDeathYearMonth;