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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0