简体   繁体   中英

Button in Repeater not raising event

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.

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?

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