如何动态地重新排序列的GridView序列、动态、GridView

2023-09-02 01:50:53 作者:心岛未晴。

类似的问题可能存在,但他们都似乎是有益的。所以我会尽力解释更具体的情况,看看是否有人能帮助我:)

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

下面是一回事,我有使用TemplateFields一个gridview,我想让用户指定这些列的显示顺序。因此,用户创建的图,并决定哪一列,以首先显示,第二,等等。

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.

一些注意事项: - 当然,我必须设置为false的AutoGenerateColumns。 - 改变SQL SELECT列顺序,因为previous项目将无法正常工作。 - 我想不是由code生成列

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.

任何想法?

推荐答案

您可以修改GridView的列集合在code-后面。所以,这样做的一种方式是从当前位置删除该列集合中,然后重新将其插入到新的位置。

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.