Web user controls are the same as ASP.NET controls. But the difference is that ASP.NET controls are those are already defined by Microsoft and we can create web user controls.
We can create our own controls in ASP.NET. If you want to develop a control which has two textboxes and one button like login control in ASP.NET 2005, you can develop in ASP.NET.
Even you can bind one or more HTML controls also into one User control with your own functionality and properties.
Open Microsoft visual studio --> File -->New website
After creating the website folder, Right click on solution explorer
-->Add New Item ---> Web User Control --> Add
Then drag and drop one text box, one label and one Button control.
And also add some functionality for those controls.(Client side script or server side script)
Here I use the javascript as client side script.
The code for web user control look like below.
<html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head2" > <title>Untitled Page</title> <script type="text/javascript"> function display() { var txt_value=document.getElementById('mycontrol1_txt1').value; if(txt_value=='') { window.alert('Please enter your name'); document.getElementById('mycontrol1_txt1').focus(); return false; } document.getElementById('mycontrol1_lbl1').innerHTML = txt_value; return false; } </script> </head> <body> <form id="form2" runat="server"> <div> <asp:Label ID="lbl1" runat="Server" ></asp:Label> <br /> <asp:TextBox ID="txt1" runat="Server" ></asp:TextBox> <br /> <asp:Button Text="Click" ID="btn" OnClientClick="return display();" runat="Server" /> </div> </form> </body> </html>
In the above code I used the javascript to display textbox value in label.
And I added the mycontrol1 to the controls id’s(textbox,label) to execute javascript. Here mycontrol1 is web control id in pages where you are using this user control.
Using the Web User control in Pages:
To use web user control in our pages,first we need to Register that control.
By using Register dirictive we can register web user control.
Nextline to the Page dirictive we need to register our control.
<%@ Register TagPrefix="usercontrol" TagName="mycontrol" Src="~/MyControl.ascx" %>
In this way we Register web user control. Here any names for tagprefix and tagname. Src reuires path of the web user control.
After Registering our Web user control, we can use this control in our code with in the page.
<usercontrol:mycontrol ID="mycontrol1" runat="Server" />
Note: Observer id of user control i.e, "mycontrol1". Remember we prefixed with same name in our usercontrol javascript.
In my next article, I will explain how to handle button click event of user control.