User Controls


In this sequence of Blogs we are going to understand about User-Controls in ASP.NET

Let us understand the basics of user-control:

A User Control is a reusable page or control with an extension of .ascx (Active Server Control eXtended) and created similar to an .aspx (Active Server Pages eXtended) page but the difference is that a User Control does not render on its own, it requires an .aspx page to be rendered.

You create ASP.NET user controls in much the same way that you design ASP.NET Web pages. You can use the same HTML elements and controls on a standard ASP.NET page. However, the user control does not have htmlbody, and form elements; and the file name extension must be .ascx.

User Controls are very useful to avoid repetition of code for similar requirements.

So let us learn practically about User Controls in depth.

Step 1: Create Web Application


Step 2: Create SQL Server Database


Step 3: Create a table ‘emp’ having two fields:

Id and Name


Step 4: Create a class for writing the queries within it

It is better to write methods in a class rather than directly writing it in code behind as it saves duplication of code and for better understandability.


Step 5: Create a Web User Control


 Step 6: In ascx file write the below code. Also add a SQLDataSource to the page

As mentioned earlier ascx file will not have HTML or BODY tag within it. It can implement only TABLE tag.


Design of the code:


Step 7: Write the below code for the click event of the Save button created in earlier step (Step 6)


Step 8: Create another Web User Control for designing GRIDVIEW


Step 9: Write the below code in the Page_Load for binding GRIDVIEW 


Step 10: Create a Web Form named Default.aspx

Register both the Web User Control pages (.ascx pages) in the default.aspx file as shown below.


Design View after registering both the ascx pages (Web User Control) to aspx page (Web Form)


Step 11: Leave the code behind blank


Step 12: Execute the website and try entering the data.




Comments are closed.