Monday 17 March 2014

How to Create Custom Control Using C# Windows Application

Step 1 : Add New User Control and design


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;

namespace UserControlExample
{
    public partial class LoginUserControl : UserControl
    {
        public LoginUserControl()
        {
            InitializeComponent();
        }

        string uName, password;

        public string UName
        {
            get { return uName; }
            set { uName = value; }
        }
        public string Password
        {
            get { return password; }
            set { password = value; }
        }

        public delegate void LoginDelegate();

        public event LoginDelegate Login_Click;

        public event LoginDelegate Clear_Click;

        private void btnLogin_Click(object sender, EventArgs e)
        {
            UName = txtUName.Text;
            Password = txtPassword.Text;

            if (string.IsNullOrEmpty(UName) || string.IsNullOrEmpty(password))
            {
                MessageBox.Show("UserName or Password is missing");
            }
            else if (UName ==password)
            {
                MessageBox.Show("UserName or Password must not same");
            }
            else
            {
                Login_Click();
            }
        }
    }
 Build the solution.....

Step 2 : Drag and Drop User control in Windows Form


Now Search for Event which is created by delegate and handle it in code behind



namespace UserControlExample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string uName, password;

        public string UName
        {
            get { return uName; }

            set { uName = value; }
        }

        public string Password
        {
            get { return password; }

            set { password = value; }
        }

        private void loginUserControl1_Login_Click()
        {
            UName = loginUserControl1.UName;
            Password = loginUserControl1.Password;

            MessageBox.Show("UNAME: " + UName + "PASSWORD: " + Password);
        }
    }
}

Output :