How to reorder columns in gridview dynamically

You can modify the Gridview’s Columns collection in your code-behind. So, one way of doing this is to remove the column from its current position in the collection and then re-insert it into the new position.

For example, if you wanted to move the second column to be the first column you could do:

var columnToMove = myGridView.Columns[1];
myGridView.Columns.RemoveAt(1);
myGridView.Columns.Insert(0, columnToMove);

If you need to move them all around randomly, then you might want to try to clone the field collection, clear the collection in the GridView, and then re-insert them all in the order you want them to be in.

var columns = myGridView.Columns.CloneFields();
myGridView.Columns.Clear();
myGridView.Columns.Add(columns[2]);
myGridView.Columns.Add(columns[0]);
etc..

I’m not 100% sure whether this all will work AFTER binding to data, so unless there’s a reason not to, I’d do it in Page_Init or somewhere before binding.

Leave a Comment