简体   繁体   中英

Click event of dynamically created Button not firing

I'm creating dynamically generated buttons, and when I click on the button, the Add_Click method doesn't get fired up.

Here is a sample from my code:

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;
}

Note : I did something very similar on page_load and it does work.

That is because when the page is reloaded, the control is most probably not recreated. That means that the event won't fire indeed.

You need to place this kind of code in the Page_Load so it gets recreated at postback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM