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.

4
  • 1
    Please give a better description of how you are adding the Button to the page. Commented Jul 18, 2013 at 20:30
  • MyControl ctl = (MyControl)LoadControl(controlPath); this.MyFormControl.Add(ctl); This happens as part of a method that is running after a button on the page is clicked. Commented Jul 18, 2013 at 20:36
  • Does btnSave_Click exist in the code-behind for the User Control or the page you are adding the UC to? Commented Jul 18, 2013 at 20:48
  • in the code-behind for the user control Commented Jul 18, 2013 at 20:55

3 Answers 3

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)?

Sign up to request clarification or add additional context in comments.

3 Comments

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?
Sadly, no, you have to create the dynamic control with each request.
+1 on the "(maybe it's in a if (!IsPostback) block)"
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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.