User Control in C#

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

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
namespace mycontrolLibrary
{
    public partial class MyCombobox : UserControl
    {
        #region Public Member
        /// <summary>
        /// Here i have create two property for geting  value of selected item of comboBox
        /// and geting text of selected item of comboBox.
        /// cmbState is a name of combobox.
        /// its neccesary property its used when you use this control
        /// in your form.
        /// </summary>
        public string SlectedText
        {
            get { return cmbState.Text; }

        }
        public string Selectedvalue
        {
            get { return cmbState.SelectedValue.ToString(); }

        }

        /// <summary>
        /// Here i have to declare event.Like Normal combobox selected indexChanged event.
        /// you can use this event whenever you have to require some action/operation on selected index
        /// changed of combobox.you have to fired this event and perform some action

        /// </summary>
        public event EventHandler SelectedIdexChanged;
        #endregion

        #region Constructor
        /// <summary>
        /// MyCombobox is a constructor.
        /// Inside constructor fire the load event of this usercontrol.
        /// </summary>
        public MyCombobox()
        {
            InitializeComponent();

            this.Load += new EventHandler(MyCombobox_Load);
            this.cmbState.SelectedIndexChanged += new EventHandler(cmbState_SelectedIndexChanged);
        }

        /// <summary>
        /// Combobox Selected indexChanged event of Combobox
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void cmbState_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (SelectedIdexChanged != null)
                SelectedIdexChanged(sender, e);

        }
        #endregion

        #region User Control Event

        void MyCombobox_Load(object sender, EventArgs e)
        {
            BindComboBox();
        }

        #endregion


        #region Binding Method
        /// <summary>
        /// This method bind combobox with specified data.
        /// </summary>
        private void BindComboBox()
        {
            DataTable dtState = new System.Data.DataTable();
            dtState.Columns.Add("txtPart");
            dtState.Columns.Add("valuePart");
            dtState.Rows.Add("Delhi", "1");//Here Delhi is txtPart and 1 is valuepart
            dtState.Rows.Add("Bihar", "2");
            dtState.Rows.Add("Punjab", "3");
            dtState.Rows.Add("UP", "4");
            cmbState.DataSource = dtState;
            cmbState.DisplayMember = "txtPart";
            cmbState.ValueMember = "ValuePart";

        }
        #endregion
    }
}


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.



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

namespace testapp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            myCombobox.SelectedIdexChanged += new EventHandler(myCombobox_SelectedIdexChanged);
        }

        void myCombobox_SelectedIdexChanged(object sender, EventArgs e)
        {
            MessageBox.Show(myCombobox.SlectedText);
        }

        private void btnDropdownSelectedvalue_Click(object sender, EventArgs e)
        {
            MessageBox.Show(myCombobox.Selectedvalue.ToString());
        }

        private void btnDropDownSelectedText_Click(object sender, EventArgs e)

        {

            MessageBox.Show(myCombobox.SlectedText);      }
      
    }
}


Happy coding.

Up Next
    Ebook Download
    View all
    Learn
    View all