单击动态创建的按钮不触发的事件

时间:2014-04-21 09:16:44

标签: c# asp.net

我正在创建动态生成的按钮,当我点击按钮时,Add_Click方法不会被启动。

以下是我的代码中的示例:

protected void SearchRec(object sender, EventArgs e)
{
    SearchResultsPanel.Controls.Clear();
    string text_to_search = SearchTB.Text;
    Friends RecToSearch = new Friends();
    List<Friends> ListNFU = DBS.getNonFriendUsers(User.Identity.Name.ToString(), text_to_search);
    if (ListNFU.Count != 0)
    {
        foreach (Friends NFRIndex in ListNFU)
        {
            string _FriendsOutput = FR_output(NFRIndex);

            HyperLink RecHyperLink = new HyperLink();
            RecHyperLink.Text = _FriendsOutput;
            RecHyperLink.CssClass = "HyperLinkFriends";
            RecHyperLink.ID = NFRIndex.UdName;

            SearchResultsPanel.Controls.Add(new LiteralControl("<div style='height:32px'>"));
            SearchResultsPanel.Controls.Add(RecHyperLink);

            Button addUser = new Button();
            addUser.CssClass = "ApproveBTN";
            addUser.Text = "send";
            addUser.Click += new EventHandler(Add_Click);
            addUser.ID = NFRIndex.UdName + "3";
            SearchResultsPanel.Controls.Add(addUser);
        }
    }
    else
    {
        Label NoResultsLabel = new Label();
        NoResultsLabel.Text = "Nothing is found";
        SearchResultsPanel.Controls.Add(NoResultsLabel);
    }
    SearchResultsPanel.Controls.Add(new LiteralControl("</div>"));
}

private void Add_Click(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    string _tempID = btn.ID;
    string id = _tempID.Substring(0, _tempID.LastIndexOf('3'));
    DateTime cdate = new DateTime();
    cdate = DateTime.Now;
    DBS.AddFriend(User.Identity.Name, id, cdate);
    btn.Visible = false;
    btn.NamingContainer.FindControl(id).Visible = false;
}

注意:我在page_load上做了一些非常相似的事情,但确实有效。

1 个答案:

答案 0 :(得分:1)

这是因为重新加载页面时,很可能无法重新创建控件。这意味着事件确实不会发生。

您需要在Page_Load中放置此类代码,以便在回发时重新创建。