0
votes

I have a DataGridView that shows summary data. It is bound to a BindingSource which is bound to a DataTable. Depending on the summary type selected by the user, the program may split the data into multiple columns. In my code, I update the existing column and add columns as needed. The new column, as expected, gets added to the end of the list and I use SetOrdinal to reposition it. The DataGridView, however never moves the column unless I blank and rebind the DataSource to the BindingSource as follows:

I add columns with the following code:

                    this.Columns.Add(newcolumn);
                    this.Columns[columnname].SetOrdinal(index++);

And I refresh the source as follows:

        teamstats.UpdateColumn(teamstats.Columns[columnClicked].ColumnName);
        bsTBAstats.DataSource = null;
        bsTBAstats.DataSource = teamstats;

This is problematic, as after I refresh the DataGridView, I have to reapply my formats (cell formts and event handlers) for each of the columns which slows down the process significantly.

Is there a more efficient way to have the DataTable refresh the column order? If the user can reorder the columns manually, why can't I do it programmatically?

1

1 Answers

0
votes

The best way I've found to accomplish what I asked above is to manually resort the columns in the DataGridView to match the order of the columns in the DataTable. The following codes shows the process I used:

        foreach (DataColumn c in teamstats.Columns)
            dgvTBAstats.Columns[c.ColumnName].DisplayIndex = teamstats.Columns.IndexOf(c);

Seems as though the binding process should automate this, but this works. Unfortunately, if the user has manually reordered the columns, that order is lost since the opposite is true and the DataTable doesn't get reordered to match the DataGridView.

I can't seem to find a better way to bind the column order.