Handling control events from Repeater footer

一个人想着一个人 提交于 2019-12-12 01:54:51

问题


Assuming I have the following repeater.

<asp:Repeater ID="MyRepeater" runat="server" onitemdatabound="MyRepeater_ItemDataBound">
    <FooterTemplate>
        </table>
        <asp:Button ID="btnPrevious" runat="server" Text="<" />
        <asp:Label ID="lblCurrentPage" runat="server" Text="<%# PagingStatus() %>" />
        <asp:Button ID="btnNext" runat="server" Text=">" />
    </FooterTemplate>
</asp:Repeater>

How can I handle the click events from btnPrevious and btnNext?

I have tried the following:

protected void MyRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    Button btnPrevious = (Button)e.Item.FindControl("btnPrevious");
    Button btnNext = (Button)e.Item.FindControl("btnNext");

    if (btnPrevious != null)
        btnPrevious.Click += btnPrevious_Click;
    if (btnNext != null)
        btnNext.Click += btnNext_Click;
}

But this has failed (The event is never raised)..


回答1:


You can use them in the same way you would use a normal button event handler eg:

Html:

<asp:Button ID="btnNext" runat="server" CommandArgument="<%=Id%>" onclick="Button_OnClick" Text=">" />

Code:

protected void Button_OnClick(object sender, EventArgs e)
{
    Button button = sender as Button;
    if(button != null)
    {
       string commandArg = button.CommandArgument;
       //Do Work
    }
}

The you can use the command argument to find out which button was clicked.
Hope this helps.




回答2:


I would suggest using the ItemCommand event of the repeater. You still have to add the commands to your buttons though. Like this:

<asp:Button ID="btnPrevious" runat="server" Text="<" CommandName="Previous"/>

protected void MyRepeater_ItemCommand(object source, RepeaterCommandEventArgs e) 
{
    if(e.CommandName.ToLower().Equals("previous")) {
        //go back
    }
    else
    {
        //go forward
    }
}


来源:https://stackoverflow.com/questions/6897141/handling-control-events-from-repeater-footer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!