Depends if you use C# or VB.
I like the C# way but I'm sure there's equivalent VB code.
Create a C# Web project with a WebForm1.aspx and WebUserControl1.ascx
Drag and drop a Button1 and Button2 to WebUserControl1.ascx
In WebUserControl1.ascx.cs define the following class members and methods (you can name them whatever you like):
Now double click the Buttons on the user control to bring up the default event handlers and call the public methods you just defined.Code:public class WebUserControl1 : System.Web.UI.UserControl { protected System.Web.UI.WebControls.Button Button1; protected System.Web.UI.WebControls.Button Button2; public delegate void FirstButtonClickHandler(); public delegate void SecondButtonClickHandler(); public event FirstButtonClickHandler FirstButtonClick; public event SecondButtonClickHandler SecondButtonClick; public void OnFirstButtonClick() { FirstButtonClick(); } public void OnSecondButtonClick() { SecondButtonClick(); } // other class code }
Drag the user control file onto WebForm1.Code:private void Button1_Click(object sender, System.EventArgs e) { OnFirstButtonClick(); } private void Button2_Click(object sender, System.EventArgs e) { OnSecondButtonClick(); }
I don't know why, but the environment doesn't declare the control in your code behind like regular controls so you have to declare it yourself. If your user control is WebUserControl1 then it should be named WebUserControl11 so I rename it uc1.
On the WebForm1 Page_Load event (or maybe the class constructor) define event handlers for the user control you just declared. After you type the '+=' Visual Studio (2003) will suggest function names and you can press tab to insert the event stub and a second time to go to the event handler function.
Code:public class WebForm1 : System.Web.UI.Page { protected WebApplication1.WebUserControl1 uc1; private void Page_Load(object sender, System.EventArgs e) { // define event handlers uc1.FirstButtonClick += new WebApplication1.WebUserControl1.FirstButtonClickHandler(uc1_FirstButtonClick); uc1.SecondButtonClick += new WebApplication1.WebUserControl1.SecondButtonClickHandler(uc1_SecondButtonClick); } private void uc1_FirstButtonClick() { Response.Write("Button1 Click"); } private void uc1_SecondButtonClick() { Response.Write("Button2 Click"); } // other class code }




Reply With Quote