简体   繁体   English

在gridview中删除列并对其重新排序,并在回发中持久化

[英]Remove and reorder columns in gridview and persisting it on postbacks

I have a page on which GridView is used to show records. 我有一个页面, 使用GridView可以显示记录。 Now I allowed the user to customize the GridView view by changing order of columns or adding removing columns from predefined list of columns. 现在,我允许用户通过更改列的顺序或添加从预定义的列列表中删除列来自定义GridView视图。 OnPagePrerender event I am removing all the cells from GridView and adding cells with the order selected by user. OnPagePrerender事件我正在从GridView中删除所有单元格,并按照用户选择的顺序添加单元格。 Its working fine but when a PostBack is occurred then it throws an exception ie 它的工作正常,但当发生PostBack时,它将引发异常,即

Failed to load ViewState. 无法加载ViewState。 etc. 等等

Because now the cells are not the same as they were saved in ViewState . 因为现在这些单元格与保存在ViewState的单元格不同。

What I want is to persist these changes that I have made to GridView on PostBack ? 我想要保留在PostBack上对GridView所做的这些更改吗?

You have to save the GridView (or your data recordset) in the VIEWSTATE and reload the Gridview only from the VIEWSTATE. 你要保存GridView中(或数据记录) VIEWSTATE并重新加载Gridview 只从 VIEWSTATE。

So in other words, only query the database when the data has to change, but you have to structure the recordset in a way that the gridview can display it, the way the data has loaded , ie dynamic SQL, with your order of columns as needed. 因此,换句话说,仅当数据需要更改时才查询数据库,但是您必须以gridview可以显示数据 recordset的方式来构造recordset ,即数据加载的方式 (即动态SQL),并且列顺序为需要。

Then save the recordset into a viewstate variable, and refer to it in your gridview when a postback is made. 然后将recordset保存到viewstate变量中,并在进行回发时在gridview引用它。

I did something similar with rows, not columns, and yeah you can't rely on the default datasource or datasourceID anymore when the gridview control is being manipulated at that deep level. 我对行而不是列做了类似的事情,是的,当在该深度gridview上操纵gridview控件时,您将不再依赖默认datasourcedatasourceID gridview

For this you have to create a new order of you Gridview columns. 为此,您必须创建一个新的Gridview列顺序。

First make copy of your columns. 首先复制您的列。 Second reorder your columns. 第二,重新排列您的列。

var columns = GridView1.Columns.CloneFields(); // makes a copy of gridview columns
GridView1.Columns.Clear(); // remove all the columns

// now make any order for your gridview columns
GridView1.Columns.Add(columns[3]); // e.g. now your column 4 is placed at first position
GridView1.Columns.Add(columns[0]); // here column 1 is placed at second position

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM