Determine sort column in a datagridview c #

0
        DataGridViewColumn sortcolum = data.SortedColumn;
        ListSortDirection dir;

        data.DataSource = "";
        /* Cargar datos */
        data.DataSource = CCarsData.ConexionDB.CargarTable();
        /* Set Grid */

        if (sortcolum != null)
        {
            if (data.SortOrder == SortOrder.Ascending)
            {
                dir = ListSortDirection.Ascending;
            }
            else
            {
                // Sort a new column and remove the old SortGlyph.
                dir = ListSortDirection.Descending;
            }

            data.Sort(sortcolum, dir);
            sortcolum.HeaderCell.SortGlyphDirection =
                dir == ListSortDirection.Ascending ?
                SortOrder.Ascending : SortOrder.Descending;
        }

I can already determine by which column the DataGridView is ordered

but when you refresh the object, and sort by the same field, it generates an error,

  {DataGridViewTextBoxColumn { Name=campo8, Index=0 }}

all this, just after refreshing the DV.

The line that causes the error:

data.Sort(sortcolum, dir);

The error message:

  

The column provided does not pertain to this DataGridView control.

    
asked by Jose Luis Tovar Fernandez 11.11.2016 в 19:00
source

1 answer

0

When you do:

data.DataSource = CCarsData.ConexionDB.CargarTable();

... this internally rebuilds the DataGridViewColumn instances that are part of the DGV. So your instance sortcolum no longer belongs to the DGV and you can not use it directly to do the sort.

What you can do is use sortcolum to find the new instance of DataGridViewColumn that does belong to the DGV and shares the same name.

Try changing:

data.Sort(sortcolum, dir);

... a:

data.Sort(data.Columns[sortcolum.Name], dir);
    
answered by 11.11.2016 / 19:33
source