Windows Forms: How to Create and use User Control in C#

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

Step 1Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "DemoUserControl" and then click OK

create user control in c#Step 2: Create a user control as below

ucState

create user control in c#

Step 3: Design your form as 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

Step 4: Create a State class to map data

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

Step 5: Add code to handle your form as below

ucState

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

namespace DemoUserControl
{
    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";
        }
    }
}

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
{
    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);
        }
    }
}

VIDEO TUTORIALS