Child User Control Button Click not working? [closed]
I have an issue with user controls. I have three user c开发者_如何学编程ontrols: Usercontrol1
, Usercontrol2
, and Usercontrol3
. Usercontrol3
has a "Submit" button. The controls are nested as follows:
default.aspx UserControl1 UserControl2 UserControl3 Submit Button
When I run my application, the submit button shows on the page, but when I click on this button, the click event is not raised. Why is this?
It's hard to tell since you haven't posted any of the code, but perhaps the issue you're encountering is that your event handler may be defined inside of the code-behind of default.aspx.cs rather than in UserControl3.ascx.cs. Your default.aspx page has no knowledge of the internal of any of its controls. This is the principle of encapsulation; default.aspx can only see the public interface of its own members, specifically UserControl1
.
I don't know the purpose of your controls, but your structure may not make sense from a componentization standpoint. It may make more sense to put the submit button in your page if it logically belongs to the page. If it truly makes sense where it is, then you may want to follow this pattern: add events to your UserControls so they are exposed to the pages/controls containing them. For example:
public class UserControl1
{
public event EventHandler Submit
{
add { this.UserControl2.Submit += value; }
remove { this.UserControl2.Submit -= value; }
}
}
public class UserControl2
{
public event EventHandler Submit
{
add { this.UserControl3.Submit += value; }
remove { this.UserControl3.Submit -= value; }
}
}
public class UserControl3
{
public event EventHandler Submit
{
add { this.SubmitButton.Click += value; }
remove { this.SubmitButton.Submit -= value; }
}
}
With this setup, the page can handle your UserControl1
's Submit
event. Another, more hacky option, in my opinion, is to attach to the submit button's event handler in your page's code by traversing its children:
protected void OnLoad(object sender, EventArgs args)
{
UserControl1.UserControl2.UserControl3.SubmitButton.Click += OnSubmit;
}
protected void OnSubmit(object sender, EventArgs args)
{
}
精彩评论