views:

53

answers:

1

When I work with the tab Ajax control, and in one tab, I have a Repeater: <asp:Repeater runat="server" ID="rp1" onitemcommand="rp1_ItemCommand"> and in protected void rp1_ItemCommand(object source, RepeaterCommandEventArgs e) method, I add a button and it's event:

Button btn = new Button();
btn.Text = "Update";
btn.Click += new EventHandler(btn_Click);
((Repeater)source).Items[0].Controls.Add(btn);

void btn_Click(object sender, EventArgs e)
{
    Response.Redirect("http://google.com");
}

However, when I click on the update button, the event is not raised.

A: 

After postback your control tree must be built up to match the tree as it were, otherwise the event does not fire if it cannot find the button in the control tree. This is probably what happens since you are manually adding the button in code-behind. Is there any particular reason why you can't have it in the template, ie.:

<asp:Repeater runat="server">
       <ItemTemplate>
           <asp:Button runat="server" OnClick="btn_Click" Text="Update" Visible="false" />
       </ItemTemplate>
   </asp:Repeater>

Then ViewState will handle it for you.

Edit: having re-read your question :) maybe you can just change the visibility of the button on ItemCommand instead of adding it because then it IS in your control tree (ie if you add it to the template). And/or if you only have "one" button (((Repeater)source).Items[**0**].Controls.Add(btn);) why not have it outside the repeater in the first place?

veggerby
I want to add dynamic button to repeater, so i do it.
may be (((Repeater)source).Items[**1**].Controls.Add(btn);) and (((Repeater)source).Items[**2**].Controls.Add(btn);) the 0 is simulator.
Then you MUST create the same buttons after postback otherwise the event wont fire - and by far the easiest way to do this is by having it in the template and NOT in code-behind! I'd recommend you read these articles on ViewState and dynamic controls: http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx and http://weblogs.asp.net/infinitiesloop/archive/2006/08/25/TRULY-Understanding-Dynamic-Controls-_2800_Part-1_2900_.aspx
veggerby