Windows forms user control

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 +

Table of Contents

  • User Controls in C#
  • Create User Control in C#
    • Test the user control, in C#
    • Summary

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

When developing Windows Forms (WinForms) applications in C#, one of the powerful features available is the ability to create custom user controls. User controls allow you to encapsulate a set of reusable UI elements and functionality into a single, easily manageable component. This not only helps in organizing your code but also promotes code reusability and maintainability. In this blog post, we will explore how to create user controls in WinForms using C#.

Why Use User Controls?

User controls offer several advantages when it comes to WinForms development:

  1. Reusability: Once created, user controls can be easily reused across multiple forms within the same project or even in different projects.

  2. Modularity: User controls promote modularity by encapsulating related UI elements and logic into a single component.

  3. Ease of Maintenance: By separating different parts of your application into user controls, you can easily update and maintain specific functionalities without affecting the rest of the application.

Steps to Create a User Control in WinForms

To create a user control in WinForms using C#, follow these steps:

  1. Create a New User Control: Right-click on your project in Visual Studio, select «Add» -> «User Control,» and give it a meaningful name.

  2. Design the User Control: In the designer view, add the necessary UI elements such as buttons, labels, textboxes, etc., and customize the layout as needed.

  3. Add Functionality: Implement the desired functionality by writing C# code in the code-behind file of the user control. You can handle events, perform calculations, or interact with other controls within the user control.

  4. Build and Compile: Build your project to compile the user control along with the rest of your application.

  5. Add User Control to Forms: To use the user control in a form, simply drag and drop it from the Toolbox onto the form’s designer view. You can then interact with the user control just like any other WinForms control.

Example: Creating a Custom User Control

Let’s create a simple custom user control that displays a welcome message and a button to close the control:

public partial class CustomUserControl : UserControl
{
    public CustomUserControl()
    {
        InitializeComponent();
        InitializeControl();
    }

    private void InitializeControl()
    {
        Label lblMessage = new Label();
        lblMessage.Text = "Welcome to Custom User Control!";
        lblMessage.Location = new Point(10, 10);
        this.Controls.Add(lblMessage);

        Button btnClose = new Button();
        btnClose.Text = "Close";
        btnClose.Location = new Point(10, 40);
        btnClose.Click += (sender, e) => this.Parent.Controls.Remove(this);
        this.Controls.Add(btnClose);
    }
}

You can now use this custom user control in your WinForms application to display a welcome message with a close button.

Conclusion

Creating user controls in WinForms using C# is a powerful way to enhance the functionality and reusability of your applications. By encapsulating related UI elements and logic into custom controls, you can build modular, maintainable, and scalable applications. Experiment with user controls in your next WinForms project and harness the benefits they offer in streamlining your development process.

Here I have to show the complete demo of How to create user control in C# window application. I have to show complete description of user control and basics of user control. After learning this document you have to be able to make user control according to own requirement. I have to cover below listed topic:

  1. Why we make User control?
  2. User control complete demo.
  3. Advantage of using User control.
  4. How to use user control?

1. Why we make User control

This Provide additional re-use flexibility with large scale web project. It’s also help to find bug and resolve bug in short time. If you want some changes in your code then you have to write code at one place (user control) that effect in every web form or every Form of window application. Using this technique you can save your extra effort and also save your time.

2. User control Complete Demo

Here I have to show the Demo make user control in window application C#.

Go to=>VS2010=>File=>Project

Go to=>Widows=>Windows Form Controls library

Write your library name and click ok.

After that I have to write code in this library.

Here I have to Show demo: My requirement is I want combo box binded with Some State Name. and because I have to use this combobox in multiple form of window application. So I have to create this user control.

1 . My design Part:Here I have drag and drop the Combobox from toolbox.

Code of:.cs file

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Drawing;  
  5. using System.Data;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9. using System.Data;  
  10. namespace mycontrolLibrary  
  11. {  
  12.     public partial class MyCombobox : UserControl  
  13.     {  
  14.         #region Public Member  
  15.           
  16.           
  17.           
  18.           
  19.           
  20.           
  21.           
  22.         public string SlectedText  
  23.         {  
  24.             get { return cmbState.Text; }  
  25.         }  
  26.         public string Selectedvalue  
  27.         {  
  28.             get { return cmbState.SelectedValue.ToString(); }  
  29.         }  
  30.           
  31.           
  32.           
  33.           
  34.   
  35.           
  36.         public event EventHandler SelectedIdexChanged;  
  37.         #endregion  
  38.  
  39.         #region Constructor  
  40.           
  41.           
  42.           
  43.           
  44.         public MyCombobox()  
  45.         {  
  46.             InitializeComponent();  
  47.             this.Load += new EventHandler(MyCombobox_Load);  
  48.             this.cmbState.SelectedIndexChanged += new EventHandler(cmbState_SelectedIndexChanged);  
  49.         }  
  50.           
  51.           
  52.           
  53.           
  54.           
  55.         void cmbState_SelectedIndexChanged(object sender, EventArgs e)  
  56.         {  
  57.             if (SelectedIdexChanged != null)  
  58.                 SelectedIdexChanged(sender, e);  
  59.         }  
  60.         #endregion  
  61.         #region User Control Event  
  62.         void MyCombobox_Load(object sender, EventArgs e)  
  63.         {  
  64.             BindComboBox();  
  65.         }  
  66.         #endregion  
  67.         #region Binding Method  
  68.           
  69.           
  70.           
  71.         private void BindComboBox()  
  72.         {  
  73.             DataTable dtState = new System.Data.DataTable();  
  74.             dtState.Columns.Add(«txtPart»);  
  75.             dtState.Columns.Add(«valuePart»);  
  76.             dtState.Rows.Add(«Delhi»«1»);  
  77.             dtState.Rows.Add(«Bihar»«2»);  
  78.             dtState.Rows.Add(«Punjab»«3»);  
  79.             dtState.Rows.Add(«UP»«4»);  
  80.             cmbState.DataSource = dtState;  
  81.             cmbState.DisplayMember = «txtPart»;  
  82.             cmbState.ValueMember = «ValuePart»;  
  83.         }  
  84.         #endregion  
  85.     }  
  86. }   

3. Advantage of using User control

  • Code re-usability.
  • Time saving.
  • Less effort.
  • Easy to find Bug and fix it.
  • Save memory also.

4. How to use User Control

Go to=>Tool Box =>right click=>Select Add tab option

After selecting add tab option write your tab name: my tab name is tets

Then Go To=>tets(Your tab) and =>Right click=>select=>Choose item

Click=>Browse button

Add your control library dll=>Select dll file and click on open button.

Here you can see your user control library has been added=>after that click ok.

After that you can see your control inside tets tab:

After adding control in tool box you can drag and drop control in your form where you want to use this control.

Its my user control you can make own user control according to own requirement.

If you want to get the custom control selected value and selected text write this code.

Here I have only show how you use property defined in custom user control.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9.   
  10. namespace testapp  
  11. {  
  12.     public partial class Form1 : Form  
  13.     {  
  14.         public Form1()  
  15.         {  
  16.             InitializeComponent();  
  17.             myCombobox.SelectedIdexChanged += new EventHandler(myCombobox_SelectedIdexChanged);  
  18.         }  
  19.   
  20.         void myCombobox_SelectedIdexChanged(object sender, EventArgs e)  
  21.         {  
  22.             MessageBox.Show(myCombobox.SlectedText);  
  23.         }  
  24.   
  25.         private void btnDropdownSelectedvalue_Click(object sender, EventArgs e)  
  26.         {  
  27.             MessageBox.Show(myCombobox.Selectedvalue.ToString());  
  28.         }  
  29.   
  30.         private void btnDropDownSelectedText_Click(object sender, EventArgs e)  
  31.         {  
  32.             MessageBox.Show(myCombobox.SlectedText);  
  33.         }   
  34.     }  
  35. } 

Happy coding.

  1. What is a UserControl C#?
  2. What is a UserControl?
  3. What is a UserControl in WPF?
  4. What is the difference between Windows form and user control?
  5. What is the meaning of WPF?
  6. What is XAML in WPF?
  7. What is CLR namespace in WPF?
  8. What is WPF MVVM?
  9. What is user control in asp net with example?
  10. How user control is different from custom control?
  11. What is the difference between user control and custom control in C#?
  12. Which property is used to set the user control on the form?
  13. Is WPF a programming language?
  14. Is WPF old technology?
  15. What is WPF and WinForms?

What is a UserControl C#?

Definition of C# User Control. C# user control is defined as an implementation in programming language of C# to provide an empty control and this control can be leveraged to create other controls. This implementation provides additional flexibility to re-use controls in a large-scale web project.

What is a UserControl?

A UserControl is a collection of controls placed together to be used in a certain way. For example you can place a GroupBox that contains Textbox’s, Checkboxes, etc. This is useful when you have to place the same group of controls on/in multiple forms or tabs.

What is a UserControl in WPF?

User controls, in WPF represented by the UserControl class, is the concept of grouping markup and code into a reusable container, so that the same interface, with the same functionality, can be used in several different places and even across several applications.

What is the difference between Windows form and user control?

User controls are a way of making a custom, reusable component. A user control can contain other controls but must be hosted by a form. Windows forms are the container for controls, including user controls. While it contains many similar attributes as a user control, it’s primary purpose is to host controls.

What is the meaning of WPF?

Windows Presentation Foundation (WPF) is a free and open-source graphical subsystem (similar to WinForms) originally developed by Microsoft for rendering user interfaces in Windows-based applications. WPF, previously known as «Avalon», was initially released as part of . NET Framework 3.0 in 2006.

What is XAML in WPF?

XAML is used extensively in Windows Presentation Foundation (WPF), Silverlight, Workflow Foundation (WF), Windows UI Library (WinUI) and Universal Windows Platform (UWP). In WPF and UWP, XAML is a user interface markup language to define UI elements, data binding, and events. In WF, however, XAML defines workflows.

What is CLR namespace in WPF?

clr-namespace: The CLR namespace declared within the assembly that contains the public types to expose as elements. assembly= The assembly that contains some or all of the referenced CLR namespace. This value is typically just the name of the assembly, not the path, and does not include the extension (such as .

What is WPF MVVM?

MVVM is a way of creating client applications that leverages core features of the WPF platform, allows for simple unit testing of application functionality, and helps developers and designers work together with less technical difficulties.

What is user control in asp net with example?

The new ASP.NET user control is created and then opened in the designer. The markup for this new control is similar to the markup for an ASP.NET Web page, except that it contains an @ Control directive instead of an @ Page directive, and the user control does not have html, body, and form elements.

How user control is different from custom control?

CustomControl is a loosely coupled control w.r.t code and UI while UserControl is a tightly coupled control w.r.t code and UI. When using CustomControl UI can be changed in different projects but for a UserControl UI is fixed and can’t have different looks in different project.

What is the difference between user control and custom control in C#?

The main difference between them- User Control is a page file with extension . ascx which can only be used within a single application or project But custom controls are assemblies(dll files) that can be used in multiple applications.

Which property is used to set the user control on the form?

User Control properties are used to set the values of a User Control from the parent page.

Is WPF a programming language?

WPF and XAML

XAML is a new descriptive programming language developed by Microsoft to write user interfaces for next-generation managed applications. XAML is used to build user interfaces for Windows and Mobile applications that use Windows Presentation Foundation (WPF), UWP, and Xamarin Forms.

Is WPF old technology?

It’s very very old. In 2003 Microsoft created . NET that made the development much easier, but deep inside, there’s still Win32 API. WPF was introduced in 2008.

What is WPF and WinForms?

The abbreviation W.P.F simply refers to Microsoft’s Windows Presentation Foundation, and WinForms is a simple concatenation of Windows Forms Applications. These are both Microsoft’s Windows Applications Graphical User Interfaces that developers may use to develop Windows desktop applications.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Bcm94313hmg2l драйвер windows 7
  • Установка сторонних тем для windows 10
  • Как выйти из установки windows 10 с флешки
  • Windows 10 как переместить папку пользователя на другой диск
  • Windows 10 show all tray icons