Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reorder columns in gridview dynamically

Similar questions may exists, but none of them seems to be helpfull. So I'll try to explain a more specific case, and see if anyone can help me :)

Here is the thing, I have a gridview with templatefields, and I want to let the user to specify the order those columns are shown. So, the user creates a view and decides which column to display first, second, and so on.

So basically, I need to change the order of the columns just after the grid is loaded with data.

Sounds easy huh? Well, apparently it's not. At least I couldn't achieve that just yet.

Some notes: - Of course I have AutogenerateColumns set to false. - Change the sql select columns order won't work because of previous item. - And I'd like not to generate the columns by the code.

Any ideas?

like image 262
Ragalante Avatar asked Jan 23 '12 17:01

Ragalante


1 Answers

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.

like image 186
patmortech Avatar answered Nov 13 '22 03:11

patmortech