I'm adding a DataGridViewComboBoxColumn
to a DataGridView
during the form's Load
event handler and setting the DataSource of each DataGridViewComboBoxCell
in the columns. However, once the form is shown, the DataSource of each DataGridViewComboBoxCell
has been set to null
. Here is the code I use to populate the column and it's cells:
DataGridViewComboBoxColumn comboCol;
comboCol = new DataGridViewComboBoxColumn();
comboCol.Name = "ComboCol";
comboCol.HeaderText = "Combo Column";
comboCol.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
this.dgv.Columns.Add(comboCol);
for (int i = 0; i < dgv.Rows.Count; i++)
{
// This datatable is actually populated here!
DataTable myData = PopulatedDataTable(dgv.Rows[i].Cells["info"].Value);
DataGridViewComboBoxCell DCC = new DataGridViewComboBoxCell();
DCC = (DataGridViewComboBoxCell)dgv.Rows[i].Cells["CombolCol"];
DCC.DataSource = myData;
DCC.DisplayMember = "Association"; // Association is a column in myData
DCC.ValueMember = "Association";
}
dgv.Columns["association"].Visible = false;
This code does exactly what is expected if I put it in a button that I click AFTER the form has loaded, but when executed during form load the DataSource is cleared. Any suggestions?
I ended up fixing this issue by handling the DataBindingComplete
event of the datagrid.
Apparently when you populate a datagrid during a form's Load
event, the data in the datagrid gets rebound. This screwed up the data in the unbound column I was trying to add.
By placing my code above in the DataBindingComplete
event handler (and disabling the event handler at the beginning and re-enabling it at the end of the event) the columns are added at the appropriate time, and their data isn't scrambled by .NET's foolishness.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With