emk
emk

Reputation: 11

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.

Upvotes: 1

Views: 2423

Answers (4)

Darthg8r
Darthg8r

Reputation: 12675

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

Upvotes: 2

Himadri
Himadri

Reputation: 8876

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
    }

Upvotes: 0

solairaja
solairaja

Reputation: 964

Try with this.

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

Upvotes: 1

Arthur
Arthur

Reputation: 8129

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)

Upvotes: 1

Related Questions