2016-11-25 30 views
0

我需要創建很多GridView s以顯示在aspx頁面上。在代碼後面排序GridView。 Gridview動態生成。 OnSorting方法不被稱爲

然後,我創建了一個方法來生成這些GridView s,它基於一組名稱和DataTable 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的名稱,它們將被動態生成(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,該錯誤仍然存​​在。

回答

1

所有你需要做的就是添加Sorting方法到GridView中GenerateGridView

Gview.Sorting += GridViewAll_Sorting; 

而對於所有的GridView的

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(); 
} 
+0

完美打造的排序方法!!!!感謝很多@VDWWD !!! –

+0

感謝這工作正常 – GGSoft