2016-08-05 30 views
1

我有很多列一個gridview。它是可排序的,允許排序=「真」,每列都有排序表達式。對於每一列的排序工作得很好,除了10列有我在Row_Databound事件動態分配標題:如何使動態列標題點擊在GridView的

protected void gvSearchResults_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.Header) 
    { 
     for (int i = 1; i < 11; i++) 
     { 
      if (Session["Label" + i.ToString()] !=null) 
      { 
       e.Row.Cells[i].Text = Session["Label" + i.ToString()].ToString(); 
      } 
     } 

    } 
} 

這10列是不能點擊。有什麼方法可以讓它們點擊嗎?這些列中的其他所有內容都可以進行排序。

我得從不同的論壇上提出了一些建議有關的Page_Load或Page_Init事件創建列,但這可能不會爲我工作。

謝謝。

回答

1

可以取代現有的LinkBut​​ton的標題單元格的文本:

protected void gvSearchResults_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.Header) 
    { 
     for (int i = 1; i < 11; i++) 
     { 
      string caption = Session["Label" + i.ToString()] as string; 

      if (caption != null) 
      { 
       TableCell headerCell = e.Row.Cells[i]; 
       LinkButton lnkSort = headerCell.Controls[0] as LinkButton; 
       lnkSort.Text = caption; 
      } 
     } 
    } 
} 
+1

我投這個答案。我根本沒有想到頭部是一個可以投射的LinkBut​​ton。 – VDWWD

0

這是可以做到。如果你看看HTML代碼,你會看到類似於GridView排序的鏈接。

<a href="javascript:__doPostBack('ctl00$mainContentPane$ctl02$GridView1','Sort$sortExpression')">yourColumnName</a> 

我們需要在RowDataBound函數中重新創建該鏈接。

for (int i = 1; i < 11; i++) 
{ 
    //first we cast the sender as a gridview 
    GridView gv = sender as GridView; 

    //get the unique ID of the gridview, this is different from ClientID which you normally would use for JavaScipt etc 
    string uniqueID = gv.UniqueID; 

    //then get the SortExpression for the column 
    string sortExpression = gv.Columns[i].SortExpression; 

    //get the new column name from the session 
    string yourColumnName = string.Empty; 
    if (Session["Label" + i.ToString()] != null) 
    { 
     yourColumnName = Session["Label" + i.ToString()].ToString(); 
    } 

    //and then we fill the header with the new link 
    e.Row.Cells[i].Text = "<a href=\"javascript:__doPostBack('" + uniqueID + "','Sort$" + sortExpression + "')\">" + yourColumnName + "</a>"; 
} 

但是,對於這個工作,enableEventValidation必須設置爲false,這是不推薦的。否則,你會得到「無效的回發或回調參數」錯誤。

更好地將之前的數據綁定到GridView以某種方式改變了列名。

0

非常感謝您的幫助。與LinkBut​​ton的解決方案對我很好:

protected void gvSearchResults_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.Header) 
    { 
     for (int i = 1; i < 11; i++) 
     { 
      if (Session["Label" + i.ToString()] !=null) 
      { 
       ((LinkButton)(e.Row.Cells[i].Controls[0])).Text = Session["Label" + i.ToString()].ToString(); 
      } 
     } 

    } 
} 
+0

這是一樣的我的答案,不是嗎?如果是這樣,你可以接受我的答案作爲正確答案。 – ConnorsFan

+0

對不起,我不知道如何做到這一點,這是我的第一篇文章在這裏。我希望我做對了。 – Peter

+0

是的,你做得對。我看到你第一次提出問題;這就是爲什麼我發表了我的評論。順便提一下,歡迎使用StackOverflow。 :-) – ConnorsFan