如何动态地将事件添加到动态创建的按钮

时间:2016-08-19 15:15:48

标签: c# asp.net events

我有一个小的ASP网络应用程序,可用于确定是否为2个用户分配了相同的座位号。

为了显示结果/功能,我决定使用asp:Table,其中每行有2个按钮(每个用户一个)。

管理员可以单击其中一个按钮,从系统中清除该用户的座位号。

以下是构建表格单元格的代码:

BuildDuplicateTable (在Page_Load中调用)

private void BuildDuplicateTable(List<Duplicate> duplicates)
{
    foreach (var dup in duplicates)
    {
        var row = new TableRow();
        var user1cell = new TableCell();
        var seatcell = new TableCell();
        var user2cell = new TableCell();

        var button1 = new Button();
        button1.Text = $"{dup.UserOne.UserName}";
        var button1cell = new TableCell();
        button1cell.Controls.Add(button1);
        button1.Click += new EventHandler(Test);

        var button2 = new Button();
        button2.Text = $"{dup.UserTwo.UserName}";
        var button2cell = new TableCell();
        button2cell.Controls.Add(button2);
        button2.OnClientClick = "return true";
        button2.Click += (sender, eventArgs) =>
        {
            ActiveDirectory.ClearProperty(dup.UserTwo.UserName, "extensionAttribute2");
        };

        user1cell.Text = dup.UserOne.UserName;
        seatcell.Text = dup.UserOne.SeatNumber;
        user2cell.Text = dup.UserTwo.UserName;

        row.Cells.Add(button1cell);
        row.Cells.Add(seatcell);
        row.Cells.Add(button2cell);

        MyAspTable.Rows.Add(row);
    }
}

我的问题是,当我点击任何按钮时,页面只会刷新,数据不再显示(因为我在Page_Load处理回发)。我的事件处理程序永远不会触发...请注意,在上面的代码中,我留下了两个单独的方法来附加我尝试过的事件处理程序 - 它们都不起作用!

复制

class Duplicate
{
    public UserSeatNumberRelationship UserOne;
    public UserSeatNumberRelationship UserTwo;

    public Duplicate(UserSeatNumberRelationship userone, UserSeatNumberRelationship usertwo)
    {
        UserOne = userone;
        UserTwo = usertwo;
    }
}

UserSeatNumberRelationship

class UserSeatNumberRelationship
{
    public string UserName;
    public string SeatNumber;

    public UserSeatNumberRelationship(string username, string seatnumber)
    {
        UserName = username;
        SeatNumber = seatnumber;
    }
}

的Page_Load

protected void Page_Load(object sender, EventArgs e)
{
    if (Page.IsPostBack) return;
    DuplicateList = FindDuplicates();
    BuildDuplicateTable(DuplicateList);
}   

测试

    protected void Test(object sender, EventArgs e)
    {
        ActiveDirectory.ClearProperty(UserName, "extensionAttribute2");
    }

1 个答案:

答案 0 :(得分:0)

正如评论中提到的 ConnersFan ,这是由PostBack中的Page_Load处理程序引起的。

删除此行后

if (Page.IsPostBack) return;

事件处理程序工作正常。