User Controls

• An user control is nothing but, user defined control.
• That means we can create our own control, and we can use it wherever required.
• The user control may contain some user interface with controls like buttons, textboxes etc.
User Control (vs) Form
Sl. No User Control Form
1 It’s a container for other controls It’s also a container for other controls.
2 It can’t run individually. It can run individually.
3 It inherits a pre-defined class called “System.Windows.Forms.UserControl”. It inherits a pre-defined class called “System.Windows.Forms.Form”.
4 It is meant for re-usability. It is meant for direct execution.

Implementation of User Controls

 Create the User Control:
 Click on “Project” menu – “Add User Control”.
 Enter the name of the new user control.
 Click on “Add”.

User Control Class Definition
namespace UserControlDemo
{
public partial class MyUserControl : UserControl
{
public MyUserControl()
{
InitializeComponent();
}
}
}
 Design and Develop the User Control:
 Design the UI in the user control, by dragging the controls from the toolbox.
 Write the code in “Code window”. (User control also supports event handlers similar to forms).

 Invoke the User Control:
 To refresh the user control, build the project.
 Then the user control name will be displayed in the toolbox automatically.
 To invoke the user control on a form, just drag it from the toolbox into the form designer.
 Then the control object will be created in the form.

user Control
MyUserControl.cs
private void btnAdd_Click(object sender, EventArgs e)
{
int n1 = Convert.ToInt32(txtFirstNo.Text);
int n2 = Convert.ToInt32(txtSecondNo.Text);
int n3 = n1 + n2;
txtResult.Text = Convert.ToString(n3);
}