First you need to define an event on your UserControl that allows the Page that contains the UserControl register and handle the event. For example:
public partial class MyUserControl : System.Web.UI.UserControl {
Note: The next part will be easier if you use a control that supports postback. However, since you want to use a div , I will explain how to get the div to do postbacks. I would like to thank Mathew Nolton for this decision.
So, in the Page_Load UserControl method, you need to add the onClick attribute to call the ASP.NET __doPostback() javascript function, which calls the server for your div . This is what gives the div ability to post back to the server. In addition, to determine which control caused the ClientId , I set the ClientId div along with some characters to distinguish my ClientId from other controls. Remember, when you define a div in a .ascx file, it must have an id assigned and set runat="server" to be available on the server side.
So, adding the onClick attribute to the div , it will be returned to the server at any time after clicking it. That way, when postback calls Page_Load to call, I check to see if it was the div that caused the postback. If so, I raise the UserControl DivClicked event, which is handled by the page.
public partial class MyUserControl : System.Web.UI.UserControl { // Event Definition and Raising methods ... protected void Page_Load(object sender, EventArgs e) { // @@@@ will denote this is an argument I provided. string arg = "@@@@" + divClickableDiv.ClientID; // Add postback method to onClick divClickableDiv.Attributes.Add("onClick", Page.ClientScript.GetPostBackEventReference(divClickableDiv, arg)); if (IsPostBack) { // Get event arguments for post back. string eventArg = Request["__EVENTARGUMENT"]; // Determine if postback is a custom postback added by me. if (!string.IsNullOrEmpty(eventArg) && eventArg.StartsWith("@@@@")) { // Raise the click event for this UserControl if the div // caused the post back. if (eventArg == arg) OnDivClicked(EventArgs.Empty); } } } }
That should do it for UserControl , now all you have to do is register for the DivClicked event on the page.
Unfortunately, you will not receive development time support for registering for the event. However, you can still add the code to the .aspx page. On the page where you drop the UserControl , add an attribute to the UserControl called OnXXX , where XXX is the name event. So, for my example above, I would define what my UserControl on the page would look like:
<uc1:MyUserControl ID="MyUserControl1" runat="server" OnDivClicked="MyUserControl1_DivClicked" />
Now you add your handler code to the Page codebehind file (assuming you use codebehind) as follows:
public partial class MyPage : System.Web.UI.Page {
That should do it. Hope this post helps you.