我有一个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#代码中向标题添加2个图像按钮,并添加一个on click事件,在填充gridview之后,我在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();
}

10-07 14:35