简体   繁体   中英

asp.net - Button event does not fire up

I have a search button on my page that runs a query on a DB, pulls out and displays some entries in a table, and for each entry I create a button. It looks something like this:

List<Friend> friends = SearchFriend(searchStr);
foreach (Friend f in friends)
{
    TableCell addCell = new TableCell(), nameCell = new TableCell();

    addCell.Text = "";
    if (!f.IsMyFriend)
    {
            LinkButton addFriendBtn = new LinkButton();
            addFriendBtn.Text = "Add as Friend";
            addFriendBtn.Click += new EventHandler(addFriendBtn_Click);
            addFriendBtn.ID = "add_" + f.ID.ToString();

            addCell.Controls.Add(addFriendBtn);
    }
    nameCell.Text = f.Name;

    TableRow row = new TableRow();
    row.Cells.Add(addCell);
    row.Cells.Add(nameCell);

    SearchFriendTable.Rows.Add(row);
}

Problem is that the LinkButton event does not fire when it is pressed (changing LinkButton to a simple Button does not fix this either).

This is the html that I get in this portion:

<td><a id="ctl00_contentPH_add_2" href="javascript:__doPostBack('ctl00$contentPH$add_2','')">Add as Friend</a></td>

Also - when I put a breakpoint on Page_Load I do see the __EVENTTARGET with this control's id in it - however the event never starts running.

Any clues? Thanks.

Adding to Himadri's answer:

Dynamically added controls need to be rewired in page init. Then the event will fire. I had a very similar issue Dynamically loaded Controls in a wizard

Where and when did you created that button?

If you dynamically create Buttons and want to listen to a event you have to create that button in the PageInit event. Always! So do not use if(!IsPostback)

试试这个。

<td><a id="ctl00_contentPH_add_2" href="javascript:__doPostBack('<%=ct100_contentPH_add_2.ClientId %>','')">Add as Friend</a></td>

Add event handler for the link buttons and handle those events.

 if (!f.IsMyFriend)
    {
            LinkButton addFriendBtn = new LinkButton();
            addFriendBtn.Text = "Add as Friend";
            addFriendBtn.Click += new EventHandler(addFriendBtn_Click);
            addFriendBtn.ID = "add_" + f.ID.ToString();
            addFriendBtn.Click += new EventHandler(addFriendBtn_Click);
            addCell.Controls.Add(addFriendBtn);
    }

the event:

  protected void addFriendBtn_Click(object sender, EventArgs e) 
        {
            LinkButton lnk = (LinkButton)sender;
            // do your coding
    }

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