Baffled by ASP.NET
Baffled by ASP.NET

Reputation: 559

How do I get dynamically added ASP.NET buttons to fire events?

This is probably a simple question but I am not an ASP.NET developer and I am quite stuck.

I have a simple search routine that returns between zero and several hundred results. Each of these must be added to the page as a button and I want to set the text of the button and the CommandArgument property so that when the button is clicked I can read the CommandArgument back and react accordingly.

However, when I click the button the event does not run at all. How can I get it to run?

The code for building the button list (simplified for readability) is as follows:

    foreach (SearchResult sr in searchResults)
    {
        Button result = new Button();
        result.Text = sr.name;
        result.CommandArgument = sr.ID.ToString();
        AccountSearchResults.Controls.Add(result);
        result.Click += new EventHandler(SearchResultClicked);
        AccountSearchResults.Controls.Add(new LiteralControl("<br/>"));
    }

At the minute to test, I have popped a label on the form to put the CommandArgument in. This code is never executed though.

   void SearchResultClicked(object sender, EventArgs e)
    {
        Label1.Text = ((Button)sender).CommandArgument;
    }

Upvotes: 2

Views: 1350

Answers (3)

BlackWasp
BlackWasp

Reputation: 4971

You mentioned in another answer that you are adding these when a button is clicked. Looking at your code, I would suggest that you try setting a unique ID for each button added, then ensure that on loading the page that buttons with the same IDs and CommandArgument values are reloaded. When a dynamically loaded button is clicked, it must still exist on the page after postback for the event to fire.

I think the ID is all you need, plus your requirement for the CommandArgument). You could put the ID information in the ViewState if you can't get it repeat without a long search process.

Upvotes: 1

Ian Oxley
Ian Oxley

Reputation: 11056

I think you need to use the OnCommand event handler, rather than the OnClick i.e. try changing this:

result.Click += new EventHandler(SearchResultClicked);

to this:

result.Command += new EventHandler(SearchResultClicked);

UPDATE

Try changing the type of second argument to your event hander from EventArgs to CommandEventArgs. You might also have to set the CommandName property on your button i.e.

result.CommandName = "foo";

Upvotes: 0

Victor
Victor

Reputation: 4721

Where are you adding this buttons?

if you are adding them inside another control then the event might be raising in the parent control. This happens on DataRepeaters and DataGrids for example.

Upvotes: 0

Related Questions