如何知道中继器中的哪个按钮被按下? [英] How can I tell which button in a repeater got pressed?

查看:157
本文介绍了如何知道中继器中的哪个按钮被按下?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在.aspx文件中具有以下标记:

I have the following markup in an .aspx file:

<asp:Repeater ID="ListOfAssignments" runat="server" OnItemDataBound="ListOfAssignments_ItemDataBound">
    <ItemTemplate>

        <asp:Label ID="AssignmentID" runat="server" Text="Label"></asp:Label>
        <br />
        <asp:Label ID="PathToFile" runat="server" Text="Label"></asp:Label>
        <br />
        <asp:Button ID="RemoveAssignment" runat="server" Text="Remove" OnClick="RemoveAssignment_Click"/>

    </ItemTemplate>
</asp:Repeater>

在相当标准的中继器控件中,有两个标签和一个按钮.中继器绑定到数据库,并使用数据库中的记录填充标签.

There are two labels and a button in a fairly standard repeater control. The repeater is bound to a database, and populates the labels with records from the database.

这是我的问题:对于中继器中的每个按钮,我都有一个click事件.当用户单击任何按钮时,将调用RemoveAssignment_Click方法.在click事件中,我想知道与用户单击的任何按钮相关联的两个标签的文本.

Here's my problem: I have a click event for each button in the repeater. The RemoveAssignment_Click method is called when the user clicks any of the buttons. In the click event, I want to know the text of the two labels associated with whatever button the user clicked.

我的意思是,用这种方法:

What I mean is, in this method:

protected void RemoveAssignment_Click(object sender, EventArgs e)
{
    //code goes here
}

我希望能够知道与单击的按钮相邻的标签的文本.我该怎么办?

I want to be able to know the text of the labels that are adjacent to the button that was clicked. How do I do that?

推荐答案

您正在寻找的是

这使您可以在网页上创建多个按钮"控件,然后 以编程方式确定单击了哪个Button控件.

This allows you to create multiple Button controls on a Web page and programmatically determine which Button control is clicked.

因此,在ListOfAssignments_ItemDataBound内部,您将CommandArgument分配给按钮,其中CommandArgument是要删除的文章的ID:

So inside ListOfAssignments_ItemDataBound you'd assign the CommandArgument to the button, where the CommandArgument is the ID of the article to be deleted:

protected void ListOfAssignments_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        Button delButton = e.Item.FindControl("RemoveAssignment") as Button;
        delButton.CommandArgument = //set to the value of AssignmentID
        //rest of your code
    }
}

现在您的按钮应该显示为使用新的OnCommand:

And now your button should say to use your new OnCommand:

<asp:Button ID="RemoveAssignment" OnCommand="RemoveAssignment" runat="server" Text="Remove" />

然后创建方法:

protected void RemoveAssignment(object sender, CommandEventArgs e)
{
    int articleIDToDelete = 0;
    if (Int32.TryParse((string)e.CommandArgument, out articleIDToDelete))
    {
        //delete the article with an ID = articleIDToDelete
    }
}

这篇关于如何知道中继器中的哪个按钮被按下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆