且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何动态重新排序gridview中的列

更新时间:2023-10-05 10:10:58

您可以在代码隐藏中修改 Gridview 的 Columns 集合.因此,执行此操作的一种方法是从集合中的当前位置移除该列,然后将其重新插入到新位置.

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);

如果您需要随机移动它们,那么您可能需要尝试克隆字段集合,清除 GridView 中的集合,然后按照您希望它们的顺序重新插入它们.

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..

我不是 100% 确定这一切在绑定到数据后是否会起作用,所以除非有理由不这样做,否则我会在 Page_Init 或绑定前的某个地方进行.

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.