在c#中,通过单击事件将图像按钮添加到gridview标头中



我有一个网格视图(下面),里面填充了项目的详细信息,我希望能够通过单击要排序的标题来对结果进行排序。

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CssClass="mGrid"
PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt" DataKeyNames="ProjectID"
OnRowDataBound="OnRowDataBound" EnableModelValidation="True" Style="width: 95%;
float: left;" AllowSorting="True">
<AlternatingRowStyle CssClass="alt"></AlternatingRowStyle>
<Columns>
    <asp:BoundField DataField="Title" HeaderText="Project Title" ItemStyle-Width="10%"
        ItemStyle-Font-Bold="true">
        <ItemStyle Width="10%" />
    </asp:BoundField>
    <asp:BoundField DataField="Division" HeaderText="Division" ItemStyle-Width="10%">
        <ItemStyle Width="10%" />
    </asp:BoundField>
    <asp:BoundField DataField="Due Date" HeaderText="Due Date" ItemStyle-Width="10%">
        <ItemStyle Width="10%" />
    </asp:BoundField>
    <asp:BoundField DataField="Status" HeaderText="Status" ItemStyle-Width="10%">
        <ItemStyle Width="10%" />
    </asp:BoundField>
</Columns>
<PagerStyle CssClass="pgr"></PagerStyle>

为了做到这一点,我在我的c#代码中添加了两个图像按钮到标题中,并添加了一个点击事件,在填充网格视图后,我在page_load中调用这个方法:

public void addHeaderFilters()
    {
        //Add to project title
        ImageButton titleAscImg = new ImageButton();
        titleAscImg.ID = "IMGB_ProjTitleAsc";
        titleAscImg.Click += new ImageClickEventHandler(sortBy_Click);
        titleAscImg.ImageUrl = "images/image";
        titleAscImg.CssClass = "sortButton";
        ImageButton titleDescImg = new ImageButton();
        titleDescImg.ID = "IMGB_ProjTitleDesc";
        titleDescImg.Click += new ImageClickEventHandler(sortBy_Click);
        titleDescImg.ImageUrl = "images/image2";
        titleDescImg.CssClass = "sortButton";
        Label lbl = new Label();
        lbl.Text = "Project Title ";
        GV_Projects.HeaderRow.Cells[2].Controls.Add(lbl);
        GV_Projects.HeaderRow.Cells[2].Controls.Add(titleAscImg);
        GV_Projects.HeaderRow.Cells[2].Controls.Add(titleDescImg);
    }
    public void sortBy_Click(object sender, EventArgs e)
    {
        ImageButton imgb = new ImageButton();
        imgb = (ImageButton)sender;
    }

这会按预期显示标题,但当我单击任一图像按钮时,事件不会触发,并且标题会从aspx代码中返回到默认值,删除箭头,我不太确定为什么?

感谢您的帮助。

看起来您需要将addHeaderFilters()封装在!IsPostBack语句

像这个

if(!IsPostBack)
{
    addHeaderFilters();
}
protected void GridViewTransaction_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.Header)
    {
        ImageButton btnExcelReport = new ImageButton();
        btnExcelReport.ID = "BtnExcelReport";
        btnExcelReport.ImageUrl = "images/excel.gif";
        btnExcelReport.ToolTip = "generate Excel report from result";
        btnExcelReport.Click += new ImageClickEventHandler(btnExcelReport_Click);
        e.Row.Cells[0].Controls.Add(btnExcelReport);
    }
}

相关内容

  • 没有找到相关文章

最新更新