对背后的代码进行分类.GridView动态生成.未调用术方法



我需要创建很多GridView s才能在ASPX页面上显示。

然后,我创建了一种基于名称数组和DataTables。

生成这些GridView S的方法

无论如何,每个GridView的生成如下:

GenerateGridView(string gvName, DataTable dtGridView){
GridView Gview = new GridView();
Gview.ID = gvName;
Gview.AutoGenerateColumns = true;
Gview.CssClass = "table table-responsive table-condensed table-striped table-bordered";
Gview.CellPadding = 4;
Gview.GridLines = 0;
Gview.AllowPaging = false;
Gview.Attributes.Add("Font-Size", "Smaller");
Gview.Attributes.Add("HeaderStyle-Font-Size", "Small");
Gview.AllowSorting = true;
}

问题:我需要OnSorting方法。但是我没有所有的GridView s名称,它们将动态生成(GVIED.ID或GRIDVIEW ID是根据Select命令的表名称动态生成的)。

所以我无法创建protected void gridViewName_OnSorting方法。

Gridview生成平滑。但是每次我单击标头时,我都会得到

system.web.httpexception

排序异常。

我创建了一个通用分类:

protected void gvSorting(object sender, GridViewSortEventArgs e) 

然后,我在GenerateGridview(..)中的所有GridView s中添加了一个属性:

Gview.Attributes.Add("OnSorting", "gvSorting");

但是,我一直在得到HTTP排序异常。我调试了代码,除了

之外

onsorting = gvsorting

出现在生成的GridView s上,该错误持续存在。

您要做的就是将Sorting方法添加到GenerateGridView

中的GridView
Gview.Sorting += GridViewAll_Sorting;

并为所有GridViews创建一个排序方法

protected void GridViewAll_Sorting(object sender, GridViewSortEventArgs e)
{
    //cast the sender as a gridview
    GridView Gview = sender as GridView;
    //get the datatable from viewstate (or another source)
    DataTable dt = ViewState["dtGridView"] as DataTable;
    //sort the datatable
    dtGridView.DefaultView.Sort = e.SortExpression;
    //bind the data to the gridview
    Gview.DataSource = dtGridView;
    Gview.DataBind();
}

最新更新