Example of C# User Controls

Combining controls that are found in the toolbox to create a composite control is possible with the user control. There may be situations where you need complex functionality and in such cases you can use a user control which has a lot of functionality in it. This would help you to modularize the code and speeds up the development.

For an example we would consider the combination of a label and a textbox and create a user control. The user control we create would have both these controls in it. Open up the Visual Studio .Net IDE and select the Web Control Library type of project.

This would create the .ascx file needed for the development of the user control. In the design view you can add two controls, namely a label and a textbox. And in the code view add the following code to set the properties for the label and the textbox.

public string propText
{
get { return TextBox1.Text; }
set { TextBox1.Text = value; }
}
public string propLbl
{
get { return Label1.Text; }
set { Label1.Text = value; }
}

Now save this project and compile this project. Now in the web page that you want to add the user control, right click the tool palette and browse to select the user control dll that we have created and add it.

This will add the user control to the tool palette. Now you can drag and drop the user control as you would with any of the other controls available in the tool box. A simple search on the internet would provide you with a lot of such examples of user controls in C#.