3

I have a user control that is loaded only in certain instances, for example, when a user clicks a button on the page the following happens:

MyControl ctl = (MyControl)LoadControl(controlPath);
this.MyFormControl.Add(ctl);

The user control that is loaded has a form and a submit button, with a method that I want to run on click so:

<asp:Button runat="server" ID="SaveButton" Text="Save" OnClick="btnSave_Click" />

In the codebehind of the user control:

protected void btnSave_Click(object sender, EventArgs e)
{
    // Do something
}

I can't seem to get the do something part to happen when the button is clicked. I think it may be related to the fact that the control is not normally loaded with the page, but I'm not really sure what to do about that.

maembe
  • 1,270
  • 1
  • 13
  • 25

3 Answers3

4

Is this in your page directive?:

<%@ Page Language="C#" AutoEventWireup="true"

Edit

Is it dynamically created/loaded? Dynamic controls need to be created every request (maybe it's in a if (!IsPostback) block)?

Mike
  • 161
  • 11
  • I'm pretty sure that this is the issue, but I'm not really sure what to do about it. It seems impractical to dynamically load the control after the postback. Is there a good way around this? – maembe Jul 18 '13 at 21:35
  • Sadly, no, you have to create the dynamic control with each request. – Mike Jul 18 '13 at 21:41
  • +1 on the "(maybe it's in a if (!IsPostback) block)" – user1132959 Mar 21 '14 at 12:25
0

Is Viewstate enabled on your page?

If you specifically turned it off, you will need to re-add your usercontrol on each post back as the page won't automatically re-add it.

AaronS
  • 7,649
  • 5
  • 30
  • 56
0

I had the same issue. I had viewstate="false" on the page I was adding the control to. (on the aspx page)

calorie712
  • 348
  • 4
  • 14