2012-02-13 15 views
2

ソートする機能を持つ2つの列を持つGridViewがあります。ソートした後、AscとDescソートのためにArrowを上下に指している列の横にイメージを表示したい。Reference ImageButton in asp.net

ImageButtonオブジェクトを参照する方法がわからないので、ImageButton.ImageUrlを、そのAscとDescの値に基づいて実際のイメージに設定できます。ここで

私の.aspxコードです:

  <Columns> 
      <asp:TemplateField> 
       <HeaderTemplate> 
       <asp:LinkButton ID="Name_SortLnkBtn" runat="server" Text="Name:" ToolTip="Click to Sort Column" CommandName="Sort" CommandArgument="Name" CausesValidation="false" /> 
       <asp:ImageButton ID="Name_SortImgBtn" runat="server" Visible="false" ToolTip="Click to Sort Column" CommandName="Sort" CommandArgument="Name" CausesValidation="false" /> 
       </HeaderTemplate>      
       <ItemTemplate> 
       <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# "~/TestResults/Diabetes.aspx?ID="+Eval("ID") %>'><%#Eval("Name")%></asp:HyperLink>          
       </ItemTemplate> 
      </asp:TemplateField> 

      <asp:TemplateField> 
       <HeaderTemplate> 
       <asp:LinkButton ID="HouseName_SortLnkBtn" runat="server" Text="House Name:" ToolTip="Click to Sort Column" CommandName="Sort" CommandArgument="House" CausesValidation="false" /> 
       <asp:ImageButton ID="HouseName_SortImgBtn" runat="server" Visible="false" ToolTip="Click to Sort Column" CommandName="Sort" CommandArgument="House" CausesValidation="false" /> 
       </HeaderTemplate>     
       <ItemTemplate><%#Eval("House")%></ItemTemplate> 
      </asp:TemplateField>     
      </Columns> 

ヘルプは素晴らしいいただければ幸いです。

更新.aspx.csファイル:

public partial class Home : System.Web.UI.Page 
{ 
    protected _code.SearchSelection _SearchSelection = new _code.SearchSelection(); 
    protected _code.Utils _utils = new _code.Utils(); 
    protected ImageButton sortImage = new ImageButton(); 
    protected void Page_Load(object sender, EventArgs e) { 
     //if (!IsPostBack) { 
     Master.FindControl("Home").ID = "active"; 
     GridView1_DataBind(); 
     //Guid ID = new Guid(_SearchSelection.getUserID().Tables[0].Rows[0]["u_ID"].ToString());    
     //} 
    } 

    protected void GridView1_DataBind() { 
     string selection = string.Empty; 
     TreeView treeMain = (TreeView)tree.FindControl("treeMain"); 
     if (treeMain.SelectedNode != null) 
      selection = treeMain.SelectedNode.Text; 
     else 
      selection = Session["Selection"].ToString(); 
     DataSet mainData = _utils.getStoreProcedure(new SqlParameter[] { new SqlParameter("@Selection", selection) }, "sp_getTenantsWithDiabetes", ConfigurationManager.ConnectionStrings["TIPS4"].ConnectionString); 
     Session["MainData"] = mainData.Tables[0]; 
     GridView1.DataSource = mainData.Tables[0]; 
     GridView1.DataBind(); 
    } 

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) { 

     //Retrieve the table from the session object. 
     DataTable dt = Session["MainData"] as DataTable; 
     ImageButton imageButton = new ImageButton(); 
     if (dt != null) { 
      //Sort the data. 
      dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression); 
      //imageButton.ImageUrl = "~/App_Themes/Sugar2006/Images/arrow_up.gif"; 
      //imageButton.Visible = true; 
      this.GridView1.DataSource = Session["MainData"]; 
      this.GridView1.DataBind(); 
     } 
    } 
    private string GetSortDirection(string column) { 

     // By default, set the sort direction to ascending. 
     string sortDirection = "ASC"; 

     // Retrieve the last column that was sorted. 
     string sortExpression = ViewState["SortExpression"] as string; 

     if (sortExpression != null) { 
      // Check if the same column is being sorted. 
      // Otherwise, the default value can be returned. 
      if (sortExpression == column) { 
       string lastDirection = ViewState["SortDirection"] as string; 
       if ((lastDirection != null) && (lastDirection == "ASC")) { 
        sortDirection = "DESC"; 
       } 
      } 
     } 

     // Save new values in ViewState. 
     ViewState["SortDirection"] = sortDirection; 
     ViewState["SortExpression"] = column; 

     return sortDirection; 
    } 

    protected void gridView1_RowDataBound(object sender, GridViewRowEventArgs e) { 
     if (e.Row.RowType == DataControlRowType.Header) {        
      var imageButton = (ImageButton)e.Row.FindControl("Name_SortImgBtn"); 
      sortImage = imageButton; 
      //imageButton.ImageUrl = "~/App_Themes/Sugar2006/Images/arrow_up.gif"; 
      //imageButton.Visible = true; 
     } 
    } 
+0

これをチェックしてください:http://stackoverflow.com/questions/7188689/change-sorting-image-button-in-gridview –

+0

お返事ありがとうございます。あなたが提供したリンクを見ると、誰かが実際の画像をクリックしてソートしますが、私の画像は表示されないので、Clickイベントに送信することはできません。 –

答えて

2

があなたのHeaderTemplateで定義されているImageButtonへの参照を取得するには、あなたがGridViewRowDataBoundイベントを配線することができます。イベントハンドラで、RowTypeプロパティを使用して行がヘッダー行かどうかを確認し、FindControlメソッドを使用してコントロールへの参照を取得します。私はあなたが正しい軌道に乗っていると思う

protected void gridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if(e.Row.RowType == DataControlRowType.Header) 
    { 
     var imageButton = (ImageButton)e.Row.FindControl("Name_SortImgBtn"); 
     imageButton.ImageUrl = "~/myimage.gif"; 
    } 
} 

EDIT

。私は、次のように変更します:

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) 
{ 
    //Retrieve the table from the session object. 
    DataTable dt = Session["MainData"] as DataTable; 
    if (dt == null) return; 

    //Sort the data 
    dt.DefaultView.Sort = e.SortExpression + " " + 
          GetSortDirection(e.SortExpression); 
    this.GridView1.DataSource = dt; 
    this.GridView1.DataBind(); 
} 

SortingイベントハンドラでImageButtonを心配する必要はありません。ヘッダー内のLinkButtonのクリックはポストバックを引き起こし、Sortingイベントハンドラが呼び出されます。 RowDataBoundイベントがトリガーされる前に実行されます(GridView1.DataBindメソッドが呼び出されるまで発生しません)。また、GetSortDirectionメソッドは、ソート式とソート順をViewStateに格納します。これらの値は、後でRowDataBoundイベントハンドラで必要になります(下記参照)。このイベントハンドラで

protected void gridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.Header) 
    { 
     //Determine sort column and sort order 
     var column = ViewState["SortExpression"] != null ? 
        ViewState["SortExpression"].ToString() : string.Empty; 
     var sortDirection = ViewState["SortDirection"] != null ? 
        ViewState["SortDirection"].ToString() : string.Empty; 

     //Find ImageButton based on sort column (return if not found) 
     var imageButtonID = string.Concat(column, "_SortImgBtn"); 
     var imageButton = e.Row.FindControl(imageButtonID) as ImageButton; 
     if(imageButton == null) return; 

     //Determine sort image to display 
     imageButton.ImageUrl = string.Equals("asc", sortDirection.ToLower()) ? 
           "~/App_Themes/Sugar2006/Images/arrow_up.gif" : 
           "~/App_Themes/Sugar2006/Images/arrow_down.gif"; 
     imageButton.Visible = true; 
    } 
} 

、我々はVisibleとその画像のURLソート方向に基づいて、使用するを作るためにどのImageButton決定するためにViewStateに格納された値を取得します。私は、ImageButtonのコントロールにカラム名プラス"_SortImgBtn"IDを与えたと仮定しました(このようにすれば、カラムをコントロール名にマッピングするswitch文を避けることができます)。 コントロールのVisibleがフロントページのfalseに設定されていて、並べ替えイメージが表示されていることを確認してください。

+0

これは、保護されたvoid GridView1_Sorting(オブジェクト送信者、GridViewSortEventArgs e)内で取得する方法を知っている素晴らしい例です。 –

+0

RowDataBound内で処理すると、どのソートを行う必要があるかわかりません。 –

+0

どのイベントが最初に起動するのですか?並べ替えがRowDataBoundより前に発生した場合は、並べ替え順序をプライベート変数に格納し、RowDataBoundでImageButtonを更新します。 RowDataBoundが最初に発生した場合は、ImageButtonへの参照をプライベート変数に格納し、Sortingから更新します。 – rsbarro