Search code examples
c#datagridviewdatasourcebindingsourcedatagridviewcheckboxcell

C# DataBound DataGridView with extra column - changes in this column are lost upon sort?


I use a DataGridView which is data-bound over a binding source. Additionally I create one CheckBoxCol on the very left for the user. Checking boxes in there and then re-sorting makes all checks disappear. Has anyone an idea how to avoid that?

Here's some code so we're on the same page ;):

    dtZg_Betr = new DataTable(); // DataTable object
    // [...] SQL SELECT and so on, I cut that stuff a bit
    adapter.Fill(dtZg_Betr); // OleDbAdapter -> fill the table with the SQL SELECT results
    // [...]
    bsZg_Betrn = new BindingSource(); // BindingSource object
    bsZg_Betrn.DataSource = dtZg_Betr;
    dgvZg_Betr.DataSource = bsZg_Betr; // bind data to DataGridView
    DataGridViewCheckBoxColumn dgvCheckBox = new DataGridViewCheckBoxColumn();
    dgvZg_Betr.Columns.Insert(0, (DataGridViewColumn)dgvCheckBox); // add additional checkbox column


    // Later on somewhere else:
    adapter.Update(dtZg_Betr); // OleDbAdapter -> update DB with table's changes

The DataGridView has no further code as such to get filled, later on of course checkbox clicks and such are handled but that should not be relevant for the issue.

Kinds regards!


Solution

  • You need an extra column in dtResult to store whether that item has been checked or not. Data controls only keep information about their items between posts if that information can be stored in the data source.