Wolf
Wolf

Reputation: 509

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.

Upvotes: 1

Views: 132

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 156918

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.

Upvotes: 1

Related Questions