Aurelio Brunod Aurelio Brunod - 1 year ago 89
ASP.NET (C#) Question

Keeping gridview column index original order

I have a dynamic gridview with the following functions:

  • You can use checkboxes to choose which columns will be visible. This is achieved like this:

    if (!chkTBDataRdo.Checked)
    grd.Columns[11].Visible = false;
    grd.Columns[11].Visible = true;

  • You can Drag&Drop labels around to choose in which order the columns will be displayed.

    if (hColumnList.Value != "")
    string[] ordine = hColumnList.Value.Split(',');

    for (int i = 0; i < ordine.Length; i++)
    var columnToMove = grd.Columns[Convert.ToInt32(ordine[i])];
    grd.Columns.Insert(i, columnToMove);


is a hidden field used to keep the field order you've set.
Everything's working fine, however when you perform a search and reorder the grid, the indexes used to perform
no longer match the original ones, and subsequent searches fail miserably because of the mismatch.

I tried rebuilding the grid every time before moving the columns around, like so:

grd.DataSource = null; //I tried with the original DataSource aswell.

I also tried storing the original grid in a Session variable, like this:

Session["grd_Orig"] = grd;

But so far none of this has worked: the grid always breaks at 2nd reorder and it looks like it's not rebuilding its original indexes.
Is there another way to do this?
Data comes from a MSSQL Database, and I'm not allowed to use any 3rd party component.

Answer Source

I solved this by adding ViewStateMode="Disabled" property to the gridview.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download