How to Create and use User Control in C#

By FoxLearn 11/26/2024 11:59:01 PM   61.2K
Creating a user control in a C# Windows Forms application is a straightforward process.

What is a User Control in C#?

A C# user control is a custom control created in C# that acts as an empty, reusable component. It can be used as a building block to create more complex controls. This implementation enhances flexibility, allowing developers to easily reuse controls in large-scale web projects, promoting modularity and efficient management of code across multiple pages or applications.

What are the purpose of User Controls in Visual C#?

The UserControl gives you the ability to create controls that can be used in multiple places within an application or organization.

In C#, a user control is a reusable component that encapsulates a set of controls and their functionality. It allows you to create custom controls with specific behaviors and properties, which can be easily reused across multiple forms or projects.

How to Create User Control in C# (Windows Forms)

Let’s walk through the steps of creating a User Control in a Windows Forms application.

Open your Visual Studio, then click New Project. Next, you need to select Visual C# on the left, then Windows and then select Windows Forms Application. Next, Enter your project name and then click OK button.

In Visual Studio, right-click on your project in the Solution Explorer, then select Add =>New Items...=>Visual C# Items =>User Control, Enter your user control name, then click OK button to create a user control.

After you finish creating a user control, you can drag and drop the Label and Combobox controls from the Visual Studio Toolbox to your user control designer.

ucState

create user control in c#

Once the user control is added, you can add properties, events, and methods to customize it.

How to add user control to form c#

To add user control to toolbox, you need to rebuild your project, then you can see your user control in the Visual Studio Toolbox.

Drag and drop the ucState and Button controls from the Visual Studio Toolbox to your form designer as shown below.

how to user a user control in c#

Another efficient use of the user control is to simply preload a ComboBox or ListBox with static items you commonly use in almost every application; some examples of this are countries/regions, cities, states, and office locations

Creating a State class to help you mapping data as shown below.

public class States
{
    public int ID { get; set; }
    public string Name { get; set; }
}

Opening your user control code behind, then modify your code as shown below.

ucState

//c# create user control
public partial class ucState : UserControl
{
    public ucState()
    {
        InitializeComponent();
    }

    public States SelectedState
    {
        get
        {
            return (States)cboState.SelectedItem;
        }
    }

    private void ucState_Load(object sender, EventArgs e)
    {
        //Init data
        List<States> list = new List<States>();
        list.Add(new States() { ID = 1, Name = "Delhi" });
        list.Add(new States() { ID = 2, Name = "Bihar" });
        list.Add(new States() { ID = 3, Name = "Punjab" });
        list.Add(new States() { ID = 4, Name = "UP" });
        cboState.DataSource = list;
        cboState.ValueMember = "ID";
        cboState.DisplayMember = "Name";
    }
}

We will initialize the sample data, then assign the DataSource to the Combobox control. You should initialize sample data in your Form_Load event handler.

Finally, Create a public property that allows you to get the selected value from the Combobox control.

Adding a click event handler to your button allows you to get the selected value from the Combobox.

Form1

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DemoUserControl
{
    //how to use user control in c# windows applicatons
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnGetState_Click(object sender, EventArgs e)
        {
            //Display data select from combobox in user control
            MessageBox.Show(string.Format("State id = {0}, name = {1}", ucState1.SelectedState.ID, ucState1.SelectedState.Name), "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}

Through this c# example, i hope so you have learned how to create user control in windows application.

VIDEO TUTORIAL