如何动态重新排序gridview中的列 [英] How to reorder columns in gridview dynamically

查看:22
本文介绍了如何动态重新排序gridview中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能存在类似的问题,但似乎都没有帮助.所以我会尝试解释一个更具体的案例,看看是否有人可以帮助我:)

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

事情就是这样,我有一个带有模板字段的 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.

一些注意事项:- 当然,我将 AutogenerateColumns 设置为 false.- 由于前一项,更改 sql 选择列顺序将不起作用.- 我不想通过代码生成列.

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

这篇关于如何动态重新排序gridview中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆