Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridViewComboBoxCell.DataSource being set to null once form is shown

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?

like image 597
Phil Downey Avatar asked Dec 21 '22 16:12

Phil Downey


1 Answers

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.

like image 67
Phil Downey Avatar answered Dec 24 '22 04:12

Phil Downey