简体   繁体   中英

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?

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.

I know this is an really old question but the suggested answer did not solve the problem fully.

The ViewState for the GridView will failed after remove / add a dynamic column.

If you need to bind any event, like OnRowCommand and OnRowUpdating, such events will not be fired.

Edit:

Look into this function if you need answers.

Protected Overrides Function CreateColumns(dataSource As PagedDataSource, useDataSource As Boolean) As ICollection

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM