How to dynamically change columns in gridview

Similar questions may exist, but none of them seem useful. So I will try to explain a more specific case and see if anyone can help me :)

Here's what, I have a gridview with templates, and I want the user to specify the display order of these columns. Thus, the user creates a view and decides which column will be displayed first, second, etc.

Basically, I need to reorder the columns immediately after loading the grid with data.

Sounds easy, huh? Well, apparently not. At least I could not achieve this yet.

Some notes: - Of course, AutogenerateColumns is set to false. - Reordering sql select columns will not work due to the previous item. - And I would not want to generate columns by code.

Any ideas?

+6
source share
1 answer

You can change the Gridview Columns collection in your code. Thus, one way to do this is to remove the column from the current position in the collection, and then reinsert it into a new position.

For example, if you want to move the second column to the first column that you could do:

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

If you need to move them around randomly, you can try to clone the collection of fields, clear the collection in the GridView, and then paste them all in the order you want them to be.

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

I'm not sure if all this will work AFTER data binding, so if there is no reason, I would do it in Page_Init or somewhere before the binding.

+18
source

Source: https://habr.com/ru/post/906688/


All Articles