Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

CSharp.NET Tutorial – Day 20



In previous article, we have discussed what is Timer, what are user defined intervals for Timer control like Interval, Tick, Start and Stop, What is the concept of Multi Document Interfaces, what are types of arrangements like Cascade (Default), TileVertical, TileHorizontal and ArrangeIcons along with some examples.

Please find below the link for accessing the article

CSharp.NET Tutorial - Day 19

Now, in this article we will discuss what are User Controls, how many ways that we can develop user controls like Creating a new control from an already existing control and Inherited or Extended controls, How to Develop a Control, classification of people who are working on Controls like Component Developer and Component Consumer, Events role in user controls, Syntax of Defining an Event, what are the Tasks of Developers and Consumers to work with Events, what are Developer Tasks, what are Consumer Tasks, How to Develop a Stop Clock Control, and finally How to Consume the Control along with some examples.

User Controls

User Controls are the controls which are created or developed or designed by developers to consume under their applications.

We can develop these user controls in two different ways which are listed below:
1)      Creating a new control from an already existing control
2)      Inherited or Extended controls

Method 1:
In this method, we can design a new control by using existing controls and then we can write our required behavior for the control.

In order to design the control, first we need to define a class as every control is a class by inheriting from the predefined class 'UserControl' which will provide us a container required for designing.

See below for better idea.

public class <Control Name> : UserControl
{

//Design the control
//Write the behavior for Control

}

Method 2:
In this method, we no need to design any control.  Here, we only copy the design of an already existing control and add new functionality or behavior that is required.  In this case, what we do is we define a class which is inheriting from the Control class, for which new behavior has to be added.

See below for better idea.

public class NumericTextBox:TextBox
{

//Write the code for accepting only numeric’s

}

Note:  In order to create a control in Method 1, we need to add an item template under the project of type as 'UserControl,' which will provide a class inheriting from 'UserControl' class, whereas in Method 2, we add an item template of type 'class' and then inherit from the control class that we want to extend.

The important thing here is we develop 'UserControls' under the Project template 'Windows Forms Control Library,' but we consume them again from 'Windows Forms' application project only.

How to Develop a Control
Here the people who are working on Controls can be classified into two types.

1)      Component Developer
2)      Component Consumer

A person who develop the control is called Component Developer and the person who consume the control is called Component Consumer.

-> While developing components, the developer of a control should first design the control, define all the required behavior to control, and then define required properties, methods and events to the control.

-> Properties can be defined to provide access for any value of the control to consumers.

Eg:  Text Property of TextBox, Checked Property of CheckBox, etc

-> We can define the methods as well so that the controls can perform any action whenever required.

Eg:  Clear() and Focus() methods of TextBox, Close () method of Form, etc

Events:
When we develop any control, we may not know what actions has to be performed at some specific time periods.

For example, the developer of Button control is not aware what should be happened when the button is clicked.  Here, what should be happened when the button is clicked should be decided by 'Component Consumer’.  Though it will be decided by Consumer, it is the responsibility of a developer to execute the code written by Consumer even if these two persons never come together to work.

To resolve the above problem, developers must first define an 'event' under their controls and then ask consumers to write code under an 'Event Procedure', which should be bounded with the 'Event' defined by the Developer, so whenever the Event occurs, Event Procedure gets executed.

Now we will see the Syntax of Defining an Event

[<modifiers>] event <delegate> <Name>

-> As we all knows usually Events take the help of 'delegates' in order to execute Event Procedures so that when we define Events we must also specify which delegate has to be used by the event to execute the event procedure.

For this, first we need to define a delegate and then Event

Eg:
public delegate void EventHandler(object sender,EventArgs e);
public event EventHandler click;

-> All the delegates which are predefined in Base Class Libraries (BCL) are usually defined with two parameters.
1)      Object sender
2)      EventArgs e

-> That's the reason why all the event procedures take the same two parameters as we already know that I/O parameters of delegate should be same as the I/O parameters of method that has to call

Note:  When we define our own events to controls, we can define delegates with or without parameters also so that the Event Procedures can also get generated with or without parameters respectively.

Now we see what are the Tasks of Developers and Consumers to work with Events

Developer Tasks
a)      Define a delegate
b)      Define a Event making use of the delegate
c)      Specify the time period when the event has to raise or occur.

Consumer Tasks
a)      Define an Event Procedure
b)      Bind the Event delegate and Event Procure

Note:  In case of consumer, the abovementioned two tasks get performed automatically when we double click on the Event in property window.

How to Develop a Stop Clock Control
-> Open a 'New Project' of type 'Windows Forms Control Library', name it as 'ControlsProject'.  By default, the project comes with a class, 'UserControl1'.  Open the Solution Explorer and rename the file as 'StopClock.cs'

-> Design the control as below


-> In the Properties of 'MaskedTextBox', set the 'Mask' property as 'type', Enter the default Text as "0000".

-> Place a 'Timer' control and set its 'interval' as '1000'.

-> Now, go to the CodeView and write the below code

Declarations

//Defining a delegate to be used under event

public delegate void MyDelegate();

//Defining an event making use of above delegate

public event MyDelegate MyClick();
int sec,min;
string secstr,minstr;

Under Timer Tick Event

if(sec<59)
sec +=1;
else
{
sec=0;
min +=1;
}
if(sec<10)
secstr="0" + sec.ToString();
else
secstr=sec.ToString();
if(min<10)
minstr="0" + min.ToString();
else
minstr=min.ToString()
else
minstr=min.ToString();
mtbTime.Text=minstr+secstr;

Under Start Button
timer1.Start();

Under Stop button
timer1.Stop();

Under Reset Button
timer1.Stop ();
mtbTime.Text="0000";
min =sec = 0;

Under Close Button

//Raising the MyClick event we defined
MyClick ();

//Defining a property to access the elapsed time

public string Time
{
get {return mtbTime.Text;
}

//Defining a method to start the stop clock

public void Start ()
{
btnStart.Enabled=false;
btnStop.Enabled=false;
timer1.Start ();
}

Now open the Solution Explorer, right click on the Project, select 'Build', which will compile the project and generate an Assembly called 'ControlsProject.dll'.

How to Consume the Control
Here, we can consume the control only from 'Windows Forms Application.'  So in order to check this, Open Windows Project, go to Toolbox, right click and select Add Tab, which will add a new tab in the Toolbox then enter a name as 'CSharp Controls.'

Now, right click on the Tab we created, select 'Choose Items,' which will open a window, click on Browse button, select 'ControlsProject.dll' we created just before from its Physical location which will add the control 'StopClock' under the Tab.

Take a new Windows Form, place a 'StopClock' control on it as well as one Button on the Form and set it's Text as "Show Time".

If we run the form directly, we can start the 'StopClock' by clicking on the 'Start' button.  If we want to start it explicitly in the Form Load, call the method Start we defined in the 'StopClock' under Form Load event.

Under Form Load
//Consuming method defined under the Control
stopClock1.Start();

Under Show Time button
//Consuming property defined under the control
MessageBox.Show(stopClock1.Time);

To consume the event defined under the control, go to the event of the control and double click on MyClick event, which will provide the event procedure 'stopClock1_MyClick()'

Under the Event Procedure, write the below code, which will get executed when you click on Close button.

this.Close ();

Inherited (or) Extended Control
MyTextBox: TextBox
-Set Options (Enumerated property)
-Any (default)
-Char
-CharOrDig
-Decimal
-AcceptDecimal (Boolean Property)
-True
-False (default)

To develop the above control, open the 'ControlsProject' in which 'StopClock' control is developed, add a Code File, naming it as MyTextBox.cs and write the below code.

using System;
using System.Windows.Forms;
namespace ControlsProject
{

public class MyTextBox:TextBox
{
public enum Options{Any,Char,CharOrDig,Digit};
options opt=0;

public options SetOption
{
get{return opt;}
set{opt = value;}
}
bool flag=false;

public bool AcceptDecimal
{
get{return flag;}
set{flag=value;}
}

public MyTextBox()
{
this.KeyPress +=new KeyPressEventHandler(MyTextBox.KeyPress);
}

private void MyTextBox KeyPress(object sender,KeyPressEventArgs e)
{
if(Convert.ToInt32(e.KeyChar)==8)
return;

switch(opt)
{
case options.Digit:
if(flag==true)
if(Convert.ToInt32(e.KeyChar)==46)
return;
if(Char.IsDigit(e.KeyChar)==false)
{
MessageBox.Show("Enter Numerics Only");
e.Handled=true;
}
break;

case options.Char:
if(Char.IsLetter(e.KeyChar)==false)
{
MessageBox.Show("Enter character only");
e.Handled=true;
}
break;

case options.CharOrDigit:
if(Char.IsLetterOrDigit(e.KeyChar)==false)
{
MessageBox.Show("Enter characters or numerics only");
e.Handled=true;
}
break;
}
}
}

Once done, Re-compile the project so that ControlsProject.dll will get re-generated.

Happy Learning….!!!!!


This post first appeared on Dot Net Programming (C#, Asp.Net, ADO.Net, WCF, WPF, Ajax, LINQ), please read the originial post: here

Share the post

CSharp.NET Tutorial – Day 20

×

Subscribe to Dot Net Programming (c#, Asp.net, Ado.net, Wcf, Wpf, Ajax, Linq)

Get updates delivered right to your inbox!

Thank you for your subscription

×