Nick Manojlovic
Nick Manojlovic

Reputation: 1171

Reference ImageButton in asp.net

I have a GridView with two columns that have capability to be sorted. After its sorted I want to display an image next to a column with Arrow pointing up or down for Asc and Desc sort.

I cannot figure out how to reference an ImageButton object so I can set the ImageButton.ImageUrl to an actual image based on if its Asc and Desc.

Here is my .aspx code:

          <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>

Help would be great appreciated.

Updated .aspx.cs file:

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;
        }
    }

Upvotes: 2

Views: 3541

Answers (1)

rsbarro
rsbarro

Reputation: 27339

To get a reference to the ImageButton defined in your HeaderTemplate, you can wire up the RowDataBound event of the GridView. In the event handler, check if the row is the header row by using the RowType property, and then use the FindControl method to get a reference to the control.

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

I think you're on the right track. I would make the following changes:

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

There's no need to worry about the ImageButton in the Sorting event handler. The click of the LinkButton in the header will cause a post back, and the Sorting event handler will be called. It will run before the RowDataBound event is triggered (that won't happen until the GridView1.DataBind method is called). Also, the GetSortDirection method will store the sort expression and the sort order in the ViewState. We'll need those values later in the RowDataBound event handler (shown below).

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;
    }
}

In this event handler, we'll retrieve the values stored in the ViewState to determine which ImageButton to make Visible and which image url to use based on the sort direction. I made the assumption that you have given the ImageButton controls an ID of the column name plus "_SortImgBtn" (if you do things in this manner you can avoid a switch statement to map the column to the control name). Just make sure that the ImageButton controls have Visible set to false in the front page and the sorting image should be displayed.

Upvotes: 2

Related Questions