C#

Create User Control in C# Winforms Applications

In this post, I would like to explain briefly that how one can make user controls in C# Winforms

The possibilities of creating own controls in C#, apart from the available out of the box controls are categorized as below

Extended Controls, by deriving from an existing control
UserControl to create a control by grouping several other controls
CustomControls, draw  control with the help of GDI +

User Controls in C#

User controls are normally a combination of more than one control in a single logical unit for achieving some specific functionality and to improve the reusability.

User controls are similar to any other class in .NET. The difference is that user controls are always derived from the UserControl class in System.Windows.Forms namespace.

User controls are segregated into partial classes for separating the logic from the designer.

User controls can be created directly inside your project.But for reusability and better maintainability, it is suggested to create user controls as separate dll, Windows Forms Control Library.

Create User Control in C#

Here I give an example of creating usercontrol in C# WinForms applications.Steps for creating a C# windows Forms user control is detailing below,

1. Open the Visual Studio and start a new project.
Select windows Control Library from Visual studio templates for Windows applications.

2. Name the project as you desired(Here I named as UserControlLibrary) and click OK.

3. Usercontrol1 will be created automatically.

4. Change the name to your desired name (Here I named LoginControl). Remember to rename it at all places properly.

5. Create your user control User Interface.In this tutorial I am just writing a small login control as below.Name the 2 textboxes as txtUserId and txtPassword and button as btnLogin

6. Write the user control code logic. An example given below (Yes, it is a simple logic just to explain only)

I have given 2 properties to the user control, UserId, and Password which user can set to some
values through the Property Window once after drag & drop the Usercontrol in the form.

In real scenarios, these properties shall be set by values retrieved from the database or any other data store.

Read the Sample code for Creating Usercontrol in C#,

using System; 
using System.Windows.Forms; 

namespace UserControlLibrary
{
    public partial class LoginControl : UserControl
    {
        public LoginControl()
        {
            InitializeComponent();
        }
 
       private string userid;
       public string UserId
       {
            get
            {
                return userid;
            }
            set
            {
                userid = value;
            }
        }
 
        private string password;
        public string Password
        {
            get
            {
                return password;
            }
            set
            {
                password = value;
            }
        }

        private void btnLogin_Click(object sender, EventArgs e)        
        {            
              if (UserId == txtUserId.Text && Password == txtPassword.Text)            
              {                 
                   MessageBox.Show("Login Successful");             
              }             
              else                
                 MessageBox.Show("Login Failed.Invalid Credentials");        
        }   
   } 
}

During Login button click user credentials are compared with the user entered login credentials in the textbox controls txtUserId and txtPassword.

Hard-coded values are assigned to Properties UserID and Password during design time.If both matches user will be allowed to log in.

Use your authentication mechanism(database driven or anything) instead of the sample here.The idea of this article is only to explain how to create UserControl with some properties and consume it.s below.This user control is ready for use now.

Test the user control, in C#

1. Create New Windows Forms Project, I named the project as TestUserControl

2. Drag & drop the User control to the form.

3. Select the Usercontrol and go to Properties window.Set UserID as “Techymedia” and Password to “Rajeev”(hardcoded to make the         logic simple)

4. Set the TestUserControl project as the startup project.

5. Run the application.You can see the following result as per the code logic.If entered User ID as “TechyMedia” and Password as “Rajeev”      the login successful message will be shown and invalid login in other cases.

Summary

This article covered user controls in C# and how to create user controls in C#.Hope you found this article helpful.If you have any queries or feedback to share on Usercontrols in C#,  write it in the comments section below.

Most of the time you need to debug the usercontrol at design time. To understand how to debug user control at design time read the article Design time debugging of User controls

Rajeev

Recent Posts

OWIN Authentication in .NET Core

OWIN (Open Web Interface for .NET) is an interface between web servers and web applications…

2 years ago

Serializing and Deserializing JSON using Jsonconvertor in C#

JSON (JavaScript Object Notation) is a commonly used data exchange format that facilitates data exchange…

2 years ago

What is CAP Theorem? | What is Brewer’s Theorem?

The CAP theorem is also known as Brewer's theorem. What is CAP Theorem? CAP theorem…

2 years ago

SOLID -Basic Software Design Principles

Some of the Key factors that need to consider while architecting or designing a software…

2 years ago

What is Interface Segregation Principle (ISP) in SOLID Design Principles?

The Interface Segregation Principle (ISP) is one of the SOLID principles of object-oriented design. The…

2 years ago

What is Single Responsibility Principle (SRP) in SOLID Design Priciples?

The Single Responsibility Principle (SRP), also known as the Singularity Principle, is a software design…

2 years ago