c# - 引用asp.net中的ImageButton

标签 c# asp.net gridview

我有一个 GridView,其中有两列,可以进行排序。排序后,我想在列旁边显示一个图像,其中箭头指向向上或向下进行升序和降序排序。

我不知道如何引用 ImageButton 对象,因此我可以根据其 Asc 和 Desc 将 ImageButton.ImageUrl 设置为实际图像。

这是我的 .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;
        }
    }

最佳答案

要获取对 HeaderTemplate 中定义的 ImageButton 的引用,您可以连接 RowDataBound GridView 的事件。在事件处理程序中,使用 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";
    }
}

编辑

我认为你走在正确的道路上。我将进行以下更改:

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。单击 header 中的 LinkBut​​ton 将导致回发,并且将调用 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;
    }
}

在此事件处理程序中,我们将检索存储在 ViewState 中的值,以确定使哪个 ImageButton 变为 Visible 以及哪个图像 url根据排序方向使用。我假设您已经为 ImageButton 控件提供了列名称的 ID 加上 "_SortImgBtn" (如果您以这种方式执行操作您可以避免使用 switch 语句将列映射到控件名称)。只需确保首页中的 ImageButton 控件的 Visible 设置为 false 即可显示排序图像。

关于c# - 引用asp.net中的ImageButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9267416/

相关文章:

C# 使用HttpContext.Current.Request 在手机浏览器上请求时无法获取QueryString e

c# - 通过 WebAPI 异步调用进程

jquery - 使用 jQuery 检查列表框项目是否存在

c# - 允许按列 gridview 排序

c# - 从 MySql 数据库收集数据后,我的 ASP.NET 应用程序不显示填充的 GridView

php - Yii2:对 GridView 中的关系计数列进行排序

c# - 方法或操作未实现 : Reset all sessions in my application

c# - 解决日期时间许可证问题的最佳方法

c# - Mongodb 在使用 Take(1) 时返回多个结果

c# - 如何加入不同的属性对象集合