How to create custom control in .NET windows application?


In this article I have explained about how to create custom controls in .Net application. For example I need custom defined text box in my windows application, i.e. text box have properties of allow alpha character only or allow numeric character only etc. In this situation we can create custom controls and implement in our .Net windows application project. Find how to create custom control in .NET windows application?

How to create custom control in .NET windows application?


Description :
Custom controls are mainly used to avoid rewrite code again. Once we create validations for text box in custom control then we cannot write code again to validate, it is reusable code.

First we need to create one custom control select File -> New -> Project -> choose visual C# windows(left side) and choose windows forms control Library template (right side) then give name of that library and click ok.
picture1

Go to solution explorer and select "user control" and delete that user control, because in this article we have to learn about custom control not user control.
picture2

Then Right on the project name in the solution explorer and select Add -> New Item
picture3

New dialogue box open select in that dialogue box "CustomControl" template and put name then click ok.
picture4

Now select one text box control from tool box and drop in the form design like below, Just drag and drop one text box in the above screen
picture5

Then double click on the form go to server side code. Code shows like below

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 ctrlLib
{
public partial class custtxtbox : Control
{
public custtxtbox()
{
InitializeComponent();
}

protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
}
}
}


We have create custom control text box so we need to change custom control class inherited from "Control" to "Text box" in the above code bold text line like this

public partial class custtxtbox : TextBox

Now create custom defined properties for the custom control text box like below

namespace WindowsFormsControlLibrary1
{
public partial class CustomControl1 : TextBox
{
//Default
//Allow number in text box
public Boolean num = false;
//Allow Charecter in text box
public Boolean c = false;
public Boolean sp = false;
public Boolean mtry = false;
public string errmsg = "";
public string msgboxtitle = "";

public CustomControl1()
{
InitializeComponent();
}

protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
}
public Boolean AllowNumericOnly
{
get { return num; }
set { num = value; Invalidate(); }
}
public Boolean AllowAlphaOnly
{
get { return c; }
set { c = value; Invalidate(); }
}

public Boolean AllowSpecialCharecterOnly
{
get { return sp; }
set { sp = value; Invalidate(); }
}

public Boolean Mandatory
{
get { return mtry; }
set { mtry = value; Invalidate(); }
}

public string ErrorMessage
{
get { return errmsg; }
set { errmsg = value; Invalidate(); }
}

public string ErrorMessageTitle
{
get { return msgboxtitle; }
set { msgboxtitle = value; Invalidate(); }
}

protected override void OnKeyPress(KeyPressEventArgs e)
{
int ascii = Convert.ToInt16(e.KeyChar);

if (ascii == 127 || ascii == 8 || ascii == 32)
{
return;
}

//Validate based on user selection

//Check user select Allow number property
if (num == true)
{
if (char.IsDigit(e.KeyChar))
{
e.Handled = false;
return;
}
}

//Check user select Alpha number property
if (c == true)
{
if (char.IsLetter(e.KeyChar))
{
e.Handled = false;
return;
}
}

//Check user select Special Charecter number property
if (sp == true)
{
if (ascii == 33 || ascii == 64 || ascii == 35 || ascii == 36 || ascii == 37 || ascii == 94 || ascii == 38 || ascii == 42 || ascii == 40 || ascii == 41 || ascii == 13)
{
e.Handled = false;
return;
}
else
{
e.Handled = true;
}
}
else
{
e.Handled = true;
}
}

//Check mandatory textbox or not
protected override void OnLeave(EventArgs e)
{
if (mtry == true)
{
if (errmsg != "")
{
if (this.Text.Length == 0)
{
MessageBox.Show(errmsg, msgboxtitle);
this.Focus();
}
}
else
{
MessageBox.Show("Text Box value cannot be blank!", "Error Information");
}
}
}
}
}

After write code go to your project property i.e. select your project right click choose properties. Below screen appear.
picture2


In application tab click "Assembly Information" then new dialogue box appear select Make assembly com-visible check box. Because we need to implement this dll in other projects, so we need to check to access methods and variables only com selected.
picture3


Then go to next tab Build (windows 7 tab as Compile) and check the "Register for COM Interop" check box.
picture4


After write all codes and change properites just build your project using Build -> Build Solution or (Ctrl + Shift + B). Now dll file for the Custom control created in Bin folder like this
picture6

Now we need to create new windows form application. Create New->Project -> select Visual C# (Windows left side) and choose "WindowsFormsApplication" template and put it name "CustmCtrlImplement" then click ok.

picture7

Go to Tool box and right click to add new tab "Custom control" in that custom control tab right click select Choose Items
picture8

Select your custom control dll file location using browse option
picture9

After that click ok to add newly created custom control added in the tool box.
picture10

Now just drag and drop the custom control text box in to the form design.
picture11

Right click on the text box control go to properties and check whether we created custom control properties are added in the Text box properties.
picture12

Now you can enable true / false in the property of the text box. After you set the validation automatically text boxes are validated in the project run time. No need to write validation code again in the form server side code.
For example I set allow only numeric true so I cannot enter alpha character in this text box during run time.
In the above form I have set like this, employee name accept only alpha character, employee age accept only numeric and employee address accept all (alpha, numeric and number series special character)
picture13

Using this custom control dll file you can implement this textbox any number of project any time. Main advantage it is used avoid rewrite of validation code in your project.
Source Code
Front End: Form design
Code Behind: C#


Attachments

  • Control_code (43122-24310-WindowsFormsControlLibrary1.rar)
  • Control_Implement (43122-24310-CustmCtrlImplement.rar)
  • Comments

    Author: Syed Arif Murshed11 Aug 2011 Member Level: Gold   Points : 0

    good one

    Guest Author: Bhargavi Bhagee08 Feb 2013

    How to create custom control in .NET windows application?

    what you are submitted here for above question... its very good..and more expanded,easy to understand. but, some errors are there in code.. when we are trying to build it is not building it is showing some errors... like

    System.valueType is a type but using like a variable

    and

    windowscontrolliobrary1.customcontrol1 doesnot contain a definition for textbox1_textchanged


    Please resolve this and give me a response to my mail id..

    its very useful for me..........
    thank you...........



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: