views:

222

answers:

2

The following code throws an InvalidOperationException with the above message and I don't understand why. My code calls the following method when the user may have made changes to the datagridview's underlying data source. The goal is to update the display with any changed data, and preserve the sort column and order.

private void ReloadDataGridBindingListFromDatabase()
        {
            DataGridView dgv = myDataGridViewControl;
            DataGridViewColumn sortedColumn = dgv.SortedColumn;
            SortOrder sortOrder = dgv.SortOrder;

            //do stuff here to refresh dgv.DataSource

            if (sortedColumn != null)
            {
                //this line throws an exception
                sortedColumn.HeaderCell.SortGlyphDirection = sortOrder;
            }

            //etc.
        }

Clearly, sortedColumn.HeaderCell is a cell that belongs to a DataGridView control. So why am I getting this exception?

Many thanks for your input.

A: 

Never mind. It's become clear to me that rebinding the datagridview's datasource destroys all the columns in the datagridview and creates new ones. So I can't hang on to a column reference across the rebinding.

The Demigeek
A: 

I ran intho this error when: Using the microsoft sample DataGridViewAutoFilterColumnHeaderCell nad Setting the datasource of the datagridview in the onload event of a window

It appears if you bind a datagridview to a datatable whose defaultView has a sort condition including one of the datagridviewautofilter columns you can get this error.

So to get around it before setting your datasource clear the sort order on the datatable defaultview

eg:

// Without this line if the sort included a column that is an // auto filter column you will get an error table.DataView.Sort = "";

dataGridView.DataSource = new BindingSource(table,null);

adamtaub