We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Tuesday, May 26, 2015

Windows Programming


-In the development of any application, we need a user interface (UI) to communicate with end-users. User interfaces are of 2 types:


   1. CUI (Character User Interface)
   2. GUI (Graphical User Interface)


-Traditionally we have only CUI, eg: Dos, Unix OS, etc., where these applications suffer from few criticisms like:

 1. They are not user-friendly, bcoz we need to learn the commands first to use them.
 2. They do not allow to navigate from one place to another.


-To solve the above problems, in the early 90's GUI applications are introduced by Microsoft with it's Windows OS, which has a beautiful feature known as 'Look & Feel'. To develop GUI's Microsoft has provided a language also in 90's only i.e VB, later when .Net has introduced the support for GUI has been given in all .net lang's.

Developing Graphical User Interfaces:


-To develop GUI we need some special components known as controls which are provided in .Net langs as classes in System.Windows.Forms namespace.

-All controls that are present under the namespace, were grouped into different categories like:
   1. Common Controls
   2. Container Controls
   3. Menu's & Tool Bar Controls
   4. Dialog Controls
   5. Reporting Controls
   6. Printing Controls
   7. Data Controls etc.,


-Whatever the control it was every control has 3 things in common:
   i) Properties: these are attributes of control which have their impact on the look of the control.
Eg: Width, Height, BackColor, ForeColor, etc.

  ii) Methods: these are actions performed by a control. Eg: Clear(), Focus(), Close(), etc.


 iii) Events: these are time periods that specifies when an action has to be performed.
Eg: Click, Load, KeyPress, MouseOver, etc.

Note: the parent class for all the controls is class "Control", which is defined with all the properties, methods and events that are common for each control like Button, TextBox, Form, Panel, etc.

-How to develop a Desktop Application (GUI)?
Ans: To develop a Desktop Application (GUI) the base control that has to be created first is Form. To create a Form define a class inheriting from the pre-defined class "Form" so that the new class also becomes a Form.
eg: public class Form1: Form


-To run the Form we have created called the static method Run of Application class by passing the object of Form we have created as a parameter.
eg: Form1 f = new Form1();
 Application.Run(f);
  or
 Application.Run(new Form1());

Note: we can develop a windows application either by using a notepad following the above process as well as under visual studio also using the "Windows Forms Application" project template.

Developing Windows Application using Notepad:


-Open notepad, write the following code in it, save, compile & then execute:

  
using System
  using System.Windows.Forms;
         public class Form1 : Form
        {
            static void Main()
            {
                Form1 f = new Form1();
                Application.Run(f);
            }
        }

Developing Windows Applications using VS:
-To develop a windows application under VS open the new project window -> select "Windows Forms Application" project template and specify a name to the project. E.g: WindowsProject

-By default the project comes with 2 classes in it:
 -Form1
 -Program

-Form1 is the class which is defined inheriting from predefined class Form.
Eg: public partial class Form1: Form

-Here the class Form1 is partial which means it is defined in multiple files:
 -Form1.cs
 -Form1.Designer.cs


Note: we will not find the Form1.Designer.cs file open by default to open it go to solution explorer expand the node Form1.cs and under it we find Form1.Designer.cs file, double click on it to open.

-Program is a static class and in this class, we find the Main method under which object of class Form1 is created for execution, as follows:
 Application.Run(new Form1());

Note: The program class is the main entry point of the project from where the execution starts.

-Windows applications developed under VS have 2 places to work with:
 1. Design View
 2. Code View

-Design View is the place where we design the app, this is accessible both to programmers and end-users whereas Code View is the place where we write code for the execution of the application, this is accessible only to programmers.
Note: because of the design view what VS provides we call it as WYSIWYG IDE (What You See Is What You Get).

Adding new Forms in the project:
-A project can contain any no. of forms in it, to add a new form under our project i.e. 'WindowsProject', open solution explorer -> right click on the project and select Add -> "Windows Form", which adds a new form Form2.cs. To run the new form goto Program class and change the code under Application. The run method as Form2.
   Eg: Application.Run(new Form2());

Properties:
-As we are aware that every control has properties, methods & events, to access the properties of a control VS provides 'Property Window' that lists all properties of a control, to open it select a control & press F4.

-We can change any property value in the list of props, under property window like Width, Height, BackColor, Font, ForeColor, etc., for which we can see the impact immediately after changing the property value. To test this go to properties of Form2 we have added right now and change any property value you want.
-Whenever we set a value to any property of control under the property window, VS on behalf of us writes all the necessary code by assigning values to the properties we have modified. We can view that code under the InitializeComponent() method of the class which is called in the constructor of the class.
-To view code under InitializeComponent method, goto Code View, right-click on the method called in the constructor and select 'Go to definition', this takes us to Form2.Designer.cs file and here also we find the same class Form2 b'coz it is partial.

Setting properties to control manually by writing the code in Notepad:


            using System;
            using System.Drawing;
            using System.Windows.Forms;
public class Form2 : Form
        {
            public Form2()
            {
                InitializeComponent();
            }
            private void InitializeComponent()
            {
                this.Text = "My Form";
                this.BackColor = Color.Pink;
                this.Size = new Size(400, 400);
            }
            static void Main()
            {
                Application.Run(new Form2());
            }
        }

Events: these are time periods which tells when an action has to be performed i.e. when exactly we want to execute a method. Every control will have no. of events under it where each event occurs on a particular time period.

-We can access the events of control also under the property window only. To view them in the property window choose events Tab on the top of the property window.
-If we want to write any code that should execute when an event occurs double click on the desired event corresponding to control, which takes you to code view and provides a method for writing the code.
-Now in our project add a new form Form3.cs, go to its Events, double click on Load Event & write the following code under Form3_Load method that is generated in Code View:
MessageBox.Show("Welcome to windows app's.");
-Again go to design view, double click on the Click Event and write following code under Form3_Click method:
MessageBox.Show("You have clicked on the form.");

Q. What happens when we double click on an event of control in the property window?

Ans: When we double click on an event in property window internally a method gets generated for writing the code & this method has a special name "Event Procedure or Event Handler", which is a block of code that is bound with an event of control and gets executed whenever the event occurs.
-The code written under event procedure will be executed by the Event when it occurs taking the help of a delegate internally as following:
-In the above case whenever the Event occurs it will call the delegate which then executes the event procedure that is bound with the event.
-Because a delegate is responsible for the execution of the event procedure first the event, delegate and  event procedure should be bound with each other as follows:
Syntax:
<control>.<event>+=new <delegate>(<event proc>)

eg:
this.Load += new EventHandler(Form3_Load);

button1.Click +=
       new EventHandler(button1_Click);

textBox1.KeyPress += new                                                KeyPressEventHandler(textBox1_KeyPress);
-Events and Delegates are predefined under BCL (Events are defined in control classes & delegates are defined under namespaces), what is defined here is only an event proc.
-After defining the event proc in form class VS links the Event, Delegate & Event Procedure as we have seen above, which can be found under the method InitializeComponent.
Note: 1 delegate can be used by multiple events to execute event proc's, but all events will not use the same delegates where different events may use different delegates to execute event proc's.

Q. How to define an Event Procedure or Event Handler manually?
Ans: To define Event Proc's or Event Handler's manually we need to follow a standard format as follows:

Syntax:
[<modifiers>] void <Name>(
  object sender, EventArgs e)
{
 <Stmts>;

}
-Event prosecutors are non-value returning methods.
-An event proc can have any name but VS adopts a convention while naming the event procedures i.e: <control name>_<event>.
Eg: Form1_Load, button1_Click, textBox1_KeyPress

Note: when we define an event procedure manually we can give any name to it as per our wish.
-Every event procedure will take 2 mandatory parameters:
 1. object sender
 2. EventArgs e

Defining Event Procedures in Notepad:
-Write the following code under a notepad file and execute it.

            using System;
            using System.Windows.Forms;
public class Form3 : Form
        {
            public Form3()
            {
                InitializeComponent();
            }
            private void InitializeComponent()
            {
                this.Text = "My New Form";
                this.Load += new EventHandler(TestProc1);
                this.Click += new EventHandler(TestProc2);
            }
            private void TestProc1(object sender, EventArgs e)
            {
                MessageBox.Show("Load Event Occurred.");
            }
            private void TestProc2(object sender, EventArgs e)
            {
                MessageBox.Show("Click Event Occurred.");
            }
            static void Main()
            {
                Application.Run(new Form3());
            }
        }

Default Events: as we are aware every control has no. of events to it, but 1 event will be the default for a Control. To write code under that default event of Control directly double click on the control which takes to an event procedure associated with that default event.

Control:   Default Event:
Form   Load
Button   Click
TextBox   TextChanged
CheckBox & RadioButton CheckedChanged
TreeView   AfterSelect
Timer   Tick
ListView, ListBox, ComboBox
& CheckedListBox              SelectedIndexChanged

Placing controls on a form:
-By default, we are provided with no. of controls where each control is a class. These controls are available in the ToolBox window on LHS of the studio, which displays all controls organized under different Tabs (groups).

-To place a control on the form either double click on desired control or select the control and place it in the desired location on the form.
Note: use the Layout toolbar to align controls properly.

Q. How does a form gets created?
Ans. When a form is added to the project internally following things take place:
   i) Defines a class inheriting from the pre-defined class Form so that the new class is also a Form.
   eg: public partial class Form1: Form ii
) Sets some initialization properties like name, text, etc., under the InitializeComponent method. 
   eg: this.Name = "Form1";
 this.Text = "Form1";


Q. How does a control gets placed on the form?
Ans: When control is placed on the form following things takes place internally:
   i) Creates an object of the appropriate control class.
   eg: 
 
            Button button1 = new Button();
            TextBox textBox1 = new TextBox();

  ii) Sets some initialization properties that are required like name, text, size, location, etc.,
   eg:

            button1.Name = "button1";
            button1.Text = "button1";
            button1.Location = new Point(x, y);

            button1.Size = new Size(width, height);

 iii) Now the control gets added to form by calling Controls. Add method on the current Form.
   eg: this.Controls.Add(button1);


Note: All the above code will be generated by VS under the InitializeComponent method within the file Designer.cs.
-The code of a windows application is divided into 2 categories:
 -Designer Code
 -Business Logic

-Code which is responsible for the construction of the form is known as designer code and code which is responsible for the execution of the form is known as business logic.
Note: Designer code is generated by VS under the
InitializeComponent method of Designer.cs file and business logic is written by programmers in the form of event proc's.

-Before .net 2.0 designer code and business logic were defined in a class present under a single file as following:
  Before 2.0


      Form1.cs:
public class Form1 : Form
        {
   -Designer Code
   -Business Logic

}

-From .net 2.0 with the introduction of partial classes designer code and business logic were separated into 2 different files but of the same class only as follows:
  From 2.0
Form1.cs:
public partial class Form1: Form
{
   -Business Logic
}

Form1.Designer.cs:
partial class Form1
{
   -Designer Code
}

Creating a form and placing a button on it using notepad:

  using System;
            using System.Drawing;
            using System.Windows.Forms;
public class Form4 : Form
        {
            Button button1;
            public Form4()
            {
                InitializeComponent();
            }
            private void InitializeComponent()
            {
                button1 = new Button();

                button1.Name = "button1";
                button1.Text = "Click Me";
                button1.BackColor = Color.Pink;
                button1.Size = new Size(100, 50);
                button1.Location = new Point(100, 100);
                button1.Click += new EventHandler(TestProc);

                this.Controls.Add(button1);
            }
            private void TestProc(object sender, EventArgs e)
            {
                MessageBox.Show("Button is clicked.");
            }
            static void Main()
            {
                Application.Run(new Form4());
            }
        }


Working with Events and Event Procedures:
The concept of events and event proc's has been derived from classical VB Lang., but there an event procedure can be bound with the only a single event of a single control, whereas in .NET it can be bound with multiple events of control as well as with multiple controls also.

Binding event procedures with multiple events of control:
-Add a new form to the project Form4 and double click on it which defines an event proc Form4_Load & bind the same event procedure with click event of form also, to do this go to events of form, select click event & click on the drop-down beside, which displays a list of event procedures available, select 'Form4_Load' event proc that is defined previously, this binds the proc with click event also now under the procedure write following code & execute:
MessageBox.Show("Bound with multiple events of control.");

Binding an event procedure with multiple controls:
-Add a new form in the project i.e. Form5 & design it as follows:

-Now define a click event procedure for button1 by double-clicking on it and bind that event procedure with button2, textBox1, textBox2 and Form5 also, then write the following code under the event proc:
MessageBox.Show("Control is clicked");

Binding an event procedure with multiple controls and then identifying the "Type" of control which is raising the event:
-Add a new form in the project i.e. Form6 & design it as follows:

-Now define a click event procedure for button1 & bind the event procedure with button2, textBox1, textBox2, and Form6 also, then write the following code under the event procedure:
            if (sender.GetType().Name == "Button")
                MessageBox.Show("Button is clicked.");
            else if (sender.GetType().Name == "TextBox")
                MessageBox.Show("TextBox is clicked.");
            else

                MessageBox.Show("Form6 is clicked.");

-When an event procedure is bound with multiple controls, any of the control can raise the event in runtime and execute the event procedure, but the control object which is raising the event will be coming into the event procedure and captured under the parameter "sender" of event procedure as following:
-As the sender is of type object it's capable of storing an object of any class in it, so after the object of the control class is captured under sender by calling GetType() method on it we can identify the type of control to which that object belongs as we have performed above.

Binding an event procedure with multiple controls and then identifying the exact control which is raising the event:

-Add a new form in the project i.e. Form7 & design it as follows:
-Now define a click event procedure for button1 & bind the event procedure with button2, textBox1, textBox2, and Form7 also, then write the following code under the event procedure:
            if (sender.GetType().Name == "Button")
            {
                Button b = sender as Button;
                if (b.Name == "button1")
                    MessageBox.Show("Button1 is clicked");
                else
                    MessageBox.Show("Button2 is clicked");
            }
            else if (sender.GetType().Name == "TextBox")
            {
                TextBox tb = (TextBox)sender;
                if (tb.Name == "textBox1")
                    MessageBox.Show("TextBox1 is clicked");
                else
                    MessageBox.Show("TextBox2 is clicked");
            }
            else
                MessageBox.Show("Form7 is clicked");



-When an event procedure is bound with multiple controls & if we want to identify the exact control which is raising the event, we need to identify the "Name" of control.
-But even if "sender" represents the control which is raising the event, using sender we cannot find the control name because as we are already aware that object of a class can be stored in its parent's variable and make it as a reference but with that reference we cannot access the child classes members (Rule No. 3 of Inheritance).
-So if we want to find the name of the control that is raising the event we need to convert the sender back into appropriate control type (Button or TextBox) from which it is created by performing an explicit conversion.
-We can convert the sender back into the Control Type in any of the following ways:
          Button b = sender as Button;
            or
           Button b = (Button)sender;

            TextBox tb = sender as TextBox;
            or

           TextBox tb = (TextBox)sender;
-So in the above program first we are converting the sender back into control type (Button or TextBox) and then finding out the name of control using Name property of that control.

Controls:
1. Button: used for taking acceptance of a user for performing an action.

2. Label: used for displaying static text on the UI.
3. TextBox: used for taking text input from the user, this control can be used in 3 different ways:
   i. Single Line Text (d)
  ii. Text Area (Multi Line Text)
 iii. Password Field

-The default behavior of the control is single-line text to make it multi-line set the property Multiline as true. By default the text area will not have scroll bars to navigate up & down, to get them set the ScrollBars property either to Vertical or Horizontal or Both.
Note: by default the WordWrap property of the control is set as true restricting horizontal scroll bar so set it as false to get a horizontal scroll bar.
-To make the control used as a password field set the PasswordChar property of the control with "*";

Setting Tab Order of Form Controls:
-While working with a windows app we navigate between controls using the Tab key of the keyboard. By default, Tab key navigates the focus between controls in the same order how they are placed on the form. If we want to set the sequence of a tab on our own, it can be done by setting the 'Tab Order'. To do this go to View Menu and select 'Tab Order' which shows the current tab order, now click on each control in a sequence how we want to move the tab, again go to view menu & select Tab Order.

-In the above form check the following business rules (Validations):
1. Check the user name, PWD & confirm pwd fields to be mandatory.
2. Check pwd to be ranging between 8 to 16 chars.
3. Check confirm pwd to be matching with pwd.
4. Enable the Save button only if the above 3 rules are satisfied.
5. Check phone TextBox to accept numerics and backspaces only.
6. Allow users to close the form if required at any time.

-To perform the first 4 validations first set the enabled property of the save button as false so that it will be in a disabled state, then set the MaxLength property of pwd textbox's to 16 so that they accept only 16 chars.
-Define a Validating event procedure for user name textbox & bind that event procedure with both pwd textboxes. Now write the following code under the Validating Event Procedure:

TextBox tb = sender as TextBox;
            if (tb.Text.Trim().Length == 0)
            {
                MessageBox.Show("Cannot leave empty.");
                e.Cancel = true;
                return;
            }
            if (tb.Name != "txtName")
            {
                if (tb.Text.Trim().Length < 8)
                {
                    MessageBox.Show("Pwd should be between 8 to    16 chars");
                    e.Cancel = true;
                    return;
                }
            }
            if (tb.Name == "txtCPwd")
            {
                if (txtPwd.Text.Trim() != txtCPwd.Text.Trim())
                {
                    MessageBox.Show("Confirm pwd should match    with pwd");
                    return;
                }
                btnSave.Enabled = true;
            }



-Validating event occurs when the focus is leaving the control and validates the content entered in the control.
-Some events are associated with properties with them eg: Validating, KeyPress, etc., if we want to consume the properties of an event under its event procedure we can make use of the parameter "e" of the event procedure which refers to properties of the currently executing event.
-In the above case, Cancel is a property of Validating event when setting as true restricts the focus not to leave the control.
-To close the form even from mandatory fields goto properties of Close Button and set its 'Causes Validation' property as false so that code under that button gets executed before the execution of any other controls validating the event.
-Now write the following code under Close Button Click Event:
txtName.CausesValidation = false;
txtPwd.CausesValidation = false;
txtCPwd.CausesValidation = false;
this.Close();

-When we set CausesValidation = false for TextBox it will restrict validating the event of the control not to occur so that focus leaves the textbox & form gets closed.
-If we want the Phone No TextBox to accept only numerics and backspace define a KeyPress event procedure for Phone No TextBox & write following code in it:
//MessageBox.Show(
                    
        Convert.ToInt32(e.KeyChar).ToString());
            if (char.IsDigit(e.KeyChar) == false && Convert.ToInt32(e.KeyChar) != 8)
            {
                MessageBox.Show("Enter numerics only");
                e.Handled = true;
            }

-KeyPress event occurs when we press & release a key while the focus is in the control.
-KeyChar property of keypress gets the key value corresponding to the key pressed.
-Handled property, when set as true, will restrict the key value to enter into the control.
-Char.IsDigit(char) will return true if the given char is a numeric or else returns false.
-Convert.ToInt32(char) will return the ascii value of the given character.

Code under Save Button:
//Need to write code for saving data to DB here
MessageBox.Show("Data saved to database");

Code under Clear Button:

foreach (Control ctrl in this.Controls)
            {
                if (ctrl.GetType().Name == "TextBox")
                {
                    TextBox tb = ctrl as TextBox;
                    tb.Clear();
                }
            }
btnSave.Enabled = false;
            txtName.Focus();

-Under Form, we have 2 properties AcceptButton & CancelButton which allows us to map buttons on a form with keyboard keys.
-AcceptButton property if bound with a button that button gets clicked whenever we press Enter key of the keyboard.
-CancelButton property if bound with a button that button gets clicked whenever we press Esc key of a keyboard.
-To set them to go to properties of form select either AcceptButton or CancelButton properties which will display the list of buttons on form select a button from them.


RadioButton & CheckBox:
-We use the controls when we want users to select from a list of values. RadioButton allows only a single value to select from a group of values whereas CheckBox allows multiple selections.

-As RadioButton's allow only a single selection when we want to use them under multiple options or questions we need to group related RadioButton's so that 1 can be selected from each group, to group them we need to place RadioButtons on separate container controls like Panel, GroupBox, TabControl, etc.
-Both these controls provide a common boolean property Checked which returns true if the control is selected or else returns false, using which we can identify which option has been chosen by the users.

Under the First Button:

             if (radioButton1.Checked)
                MessageBox.Show("Radio Button1 is selected");
            else if (radioButton2.Checked)
                MessageBox.Show("Radio Button2 is selected");
            else if (radioButton3.Checked)
                MessageBox.Show("Radio Button3 is selected");

Under Second Button:

            if (checkBox1.Checked)
                MessageBox.Show("Check Box1 is selected");
            if (checkBox2.Checked)
                MessageBox.Show("Check Box2 is selected");
            if (checkBox3.Checked)
                MessageBox.Show("Check Box3 is selected");

Declarations:
int count = 0;

Define a CheckedChanged event for 1 CheckBox, bind with the remaining Check Box's & then write following code under the event procedure:

int amt = int.Parse(txtFees.Text);
            CheckBox cb = sender as CheckBox;
            if (cb.Checked)
            {
                count += 1;
                amt += Convert.ToInt32(cb.Tag);
            }
            else
            {
                count -= 1;
                amt -= Convert.ToInt32(cb.Tag);
            }
            txtFees.Text = amt.ToString();
            if (count == 0)
                radioButton1.Checked = true;

Define a CheckedChanged event for 1 radio button, bind with the remaining radio button's & then write following code under the event procedure:

int amt = int.Parse(txtFees.Text);
            if (amt > 0)
            {
                RadioButton rb = sender as RadioButton;
                if (rb.Checked)
                    amt += Convert.ToInt32(rb.Tag);
                else
                    amt -= Convert.ToInt32(rb.Tag);
                txtFees.Text = amt.ToString();
            }
            else
                radioButton1.Checked = true;

            Under Clear All Button:
foreach (Control ctrl in groupBox1.Controls)
            {
                if (ctrl.GetType().Name == "CheckBox")
                {
                    CheckBox cb = ctrl as CheckBox;
                    cb.Checked = false;
                }
            }

ComboBox, ListBox, CheckedListBox:

-These controls are also used for users to select from a list of available values.
-ComboBox allows only a single selection but it was editable which gives a chance to either select from the available values or enter a new value.
-ListBox by default allows single selection only but can be customized to multi-selection.
-CheckedListBox by default allows multi-selection.
Adding values to the controls:
-We can add values to the 3 controls in diff. ways:
i) In the properties of the control, we find a property Items, select it and click on the button beside it which opens a window, enter the values you want to add each in a new line.
ii) Using Items.The add method of the control values can be added one at a time.
 <control>.Items.Add(object value)
iii) Using Items.AddRange method of the control an array of values can be added at a time.
 <control>.Items.AddRange(object[] values)
iv) Using DataSource property of the control a DB table can be bound to it, but as it can display only a single column we need to specify the column to be displayed using the DisplayMember property.
   <control>.DataSource = <data table>
   <control>.DisplayMember = <col name>
Multi-Selection for ListBox:
ListBox control by default allows single selection only but by changing the SelectionMode property either to MultiSimple or MultiExtended multi selection is possible.
   -SelectionMode
    -None
 -One [d]

 -MultiSimple  [Only mouse click]
 -MultiExtended [Ctrl + Mouse click]

Identifying selected values from the controls:
ComboBox:
 -Text  string
 -SelectedItem object
 -SelectedIndex int

ListBox:
 -SelectedItem object
 -SelectedIndex int
 -SelectedItems object[]
 -SelectedIndices int[]

CheckedListBox:
 -CheckedItems object[]
 -CheckedIndices int[]

Under Form Load:
listBox1.Items.Add("AP");
listBox1.Items.Add("Tamilnadu");
---<List of states in the same way>---

string[] cities = { "Hyderabad", "Chennai", "Delhi",             "Bengluru", "Mumbai", , "Kolkota" };
checkedListBox1.Items.AddRange(cities);

Under ComboBox KeyPress:
//Adds value to comboBox in runtime
if (Convert.ToInt32(e.KeyChar) == 13)
   if(comboBox1.FindString(comboBox1.Text) == -1)
      comboBox1.Items.Add(comboBox1.Text); 

FindString(string value): returns the index position of the given value under the control.
FindStringExact(string value): same as above but checks with the case also.

Under First Button:


MessageBox.Show(comboBox1.Text);
            MessageBox.Show(
             comboBox1.SelectedItem.ToString());
            MessageBox.Show(
             comboBox1.SelectedIndex.ToString());

Under Second Button:

foreach (object obj in listBox1.SelectedItems)
   MessageBox.Show(obj.ToString());  

Under Third Button:

string str = null;
            foreach (object obj in checkedListBox1.CheckedItems)
                str += obj.ToString() + ", ";
            str = str.Substring(0, str.Length - 2);
            int pos = str.LastIndexOf(",");
            if (pos != -1)
            {
                str = str.Remove(pos, 1);
                str = str.Insert(pos, " &");
            }
            MessageBox.Show(str);

SelectedIndexChanged: it is the default event of all the above 3 controls which gets raised once a value gets selected from them.

Declarations:

  string[] q1 = { "January", "February", "March" };
            string[] q2 = { "April", "May", "June" };
            string[] q3 = { "July", "August", "September" };
            string[] q4 = { "October", "November", "December" };

Under ComboBox1 SelectedIndexChanged:

comboBox2.Items.Clear();
            switch (comboBox1.SelectedIndex)
            {
                case 0:
                    comboBox2.Items.AddRange(q1);
                    break;
                case 1:
                    comboBox2.Items.AddRange(q2);
                    break;
                case 2:
                    comboBox2.Items.AddRange(q3);
                    break;
                case 3:
                    comboBox2.Items.AddRange(q4);
                    break;
            }

PictureBox:
-we use it for displaying images within an app. To bind an image to the control we can use any of the following properties:
   -ImageLocation = <path of the image>
   -Image = Image.FromFile(<path of the image>)
   -Image = Image.FromStream(Stream stream) 

-Use BorderStyle property to control what type of border we want for the PictureBox, with any of the following values:
 -None [d]
 -FixedSingle
 -Fixed3d

-Use SizeMode property of the control to set image placement & control sizing under the PictureBox which can be set with any of the following:
 -Normal [d]
 -StretchImage
 -AutoSize
 -CenterImage

Dialog Controls: these are used for displaying a list of system values from which the users can select. We have 5 different dialog controls in .Net like ColorDialog, FolderBrowserDialog, FontDialog, OpenFileDialog & SaveFileDialog.

-None of the dialog controls are shown directly on the form even after adding them we can see them only at the bottom of a studio in the design time, to make them visible in runtime we need to explicitly call the method ShowDialog() which is same for all the 5 controls.
-Dialog Controls never performs any action they are only responsible for returning the value that has been chosen by the user to the programmer who is responsible for performing the necessary actions. To capture the values that are chosen by end-users we are provided with the following properties:
   -ColorDialog  Color
   -FolderBrowserDialog SelectedPath
   -FontDialog  Font
   -OpenFileDialog  FileName
   -SaveFileDialog  FileName

Under Change Color Button:
colorDialog1.ShowDialog();
button1.BackColor = colorDialog1.Color;

Under Change Font Button:
fontDialog1.ShowDialog();
button2.Font = fontDialog1.Font;

Under Load Image Button:
openFileDialog1.ShowDialog();
pictureBox1.ImageLocation = openFileDialog1.FileName;

Under Save Image Button:
saveFileDialog1.ShowDialog();
pictureBox1.Image.Save(
  saveFileDialog1.FileName); 
MaskedTextBox:
-It is the same as a TextBox but can be used for taking the input in some specific formats from the user. To set a format for input, select the Mask property in property window & click on the button beside it which opens a window in it either choose from the list of available masks or select custom and specify your own format using zeros in the masked textbox below as following:
   -Railway PNR: 000-0000000
   -CC No.:  0000-0000-0000-0000
   -Short Date: 00/00/00

Timer Control: it's a control that can perform an action regularly at a specified interval similar to a button that performs the action only after we click on it.

Members of Timer:
1. Tick: an event under which we need to write the code that has to be executed.
2. Interval: a property using which we specify the frequency of execution in milliseconds.
3. Start(): a method to start the execution of a timer.
4. Stop(): a method to stop the execution of a timer.

Adding Menus to a Form: 
-To add menu's to Form first we need to place a MenuStrip control on Form which is present under Menu's & ToolBar's Tab of ToolBox, which sits on top of the Form.


-To add a Menu on MenuStrip click on LHS corner of it which shows a textbox asking to 'Type Here', enter a name in it which adds a Menu, repeat the same process for adding of multiple Menu's.

-To add a MenuItem under a menu, click on the menu which shows a textbox below asking to 'Type Here', enter a name in it which adds a MenuItem, repeat the same process for adding of multiple MenuItem's.

Note: both Menu & MenuItem are objects of class ToolStripMenuItem.

-If we want menus to be responding for "Alt Keys" of keyboard prefix with "&" before the character that should respond to Alt.
 eg: &File     &Edit     F&ormat 


-To create a shortcut for MenuItems so that they respond to keyboard actions, go to properties of MenuItem, select "ShortcutKeys" Property, click on the drop down beside it, which displays a window, in it choose a modifier Ctrl or Alt or Shift & then choose a Key from ComboBox below.

-To group related MenuItems under a Menu we can add separators between MenuItems, to do it right-click on a MenuItem & select Insert -> separator which adds a separator on top of the MenuItem.
Note: same as we inserted a separator we can also insert a MenuItem if required, in the middle.

-If we want to display any Image beside MenuItem right-click on it & select "Set Image" which opens a window, select Local Resource & click on Import button which opens a DialogBox, using it select an image from your Hard disk.

-Some times we find checkmarks beside MenuItem to identify a property is on or off, eg: WordWrap under Notepad. To create check mark's beside a MenuItem right-click on it and select "Checked".
Note: to check or uncheck the item in run time we need to write code explicitly under click event of MenuItem as following:
 if (<control>.Checked == true)
       <control>.Checked = false;
 else
       <control>.Checked = true;


Multi-Document Interface:
-While designing an application it can contain any no. of forms in it, right now to run the desired form we are explicitly specifying the form class name under Program class. But, when we provide the app. to the client we only give him the assemblies of the project (i.e. IL Code) so the client doesn't have a chance to edit the class Program and specify the form class name he wants to run.


-To overcome the above problem we are provided with an approach known Multi-Document Interface where in this approach an app. will be having only one form as a start-up Form which is referred as MdiParent or MdiContainer so that clients don't require to change the form name under program class at any time. The rest of the forms in-app. will be under the control of MdiParent Form and referred to as MDI Child. To make a form as MdiParent sets the property IsMdiContainer as true.

Note: an application can have only one MdiParent and all other forms must be child's of a parent who should come and sit under the parent. Eg.: VS is an MdiParent that launches all other forms like "New Project", "Add New Item" windows as its child's.

-To launch a form as a child of parent create an object of child form class, set its MdiParent property with parent forms reference & then call Show() method.
Layout:
-When we have more than one child form opened at a time under the parent, child forms will be arranged inside the parent by using a layout for arrangement, which can be any of the following 4 options like:

i) Cascade (d): child forms are arranged 1 on top of the other.
ii) TileVertical: child forms are arranged 1 beside the other.
iii) TileHorizontal: child forms are arranged 1 below the other.
iv) ArrangeIcons: all child forms icons are arranged within the bottom of the parent.

-Now add a new Form in the Project naming it as MdiParent.cs, set its IsMdiContainer property as true to make it as a MdiParent and also set the WindowState property as Maximized so that form gets launched to the full size of the screen.


-Add a MenuStrip control to the Form and place 2 menu's on it: Forms and Layout.

-Under Forms Menu add a MenuItem for each child form to launch e.g: Form1, Form2, Form3, etc.
-Under Layout Menu add the following MenuItems: ArrangeIcons, Cascade, Horizontal, Vertical.

-Now write the following code in Code View:
Under Each Form's MenuItems:
Form1 f = new Form1();
f.MdiParent = this;
f.Show();

Under Arrange Icons MenuItem:
this.LayoutMdi(MdiLayout.ArrangeIcons);


Under Cascade MenuItem:
this.LayoutMdi(MdiLayout.Cascade); 

Under Vertical MenuItem:
this.LayoutMdi(MdiLayout.TileVertical); 

Under Horizontal MenuItem:this.LayoutMdi(MdiLayout.TileHorizontal);

User Controls:
-These are components that will be developed by application developers to consume under any app.

-User Controls will be developed in 2 ways:
   -Creating a new control from existing controls
   -Inherited or extended controls


-In the first case, we design a new control making use of existing controls & then write the required behavior for control. To design the control first we need to define a class (because every control is a class) inheriting from the predefined class User Control which provides a container required for designing.
public class <ControlName> : UserControl
{
  //Design the control
  //Write the behavior for control

}


-In the second case, we don't design anything newly, we only copy the design of an existing control for adding new functionalities or behavior that is required. In this case, we define a class that is inheriting from the control class for which new behavior has to be added.
public class NumericTextBox : TextBox
{
 //write the code for accepting only numeric
}


-To create control in the first process we need to add UserControl ItemTemplate in the project which provides a class that is inheriting from UserControl class, whereas in the second case we need to add Class ItemTemplate & then inherit from the control class we want to extend.

Note: to develop UserControls we are provided with the Windows Forms Control Library project template. But the controls whatever we develop are finally consumed from Windows Forms Application project templates only.

People working on controls are classified as:
   1. Component Developers
   2. Application Developers


-The persons who develop controls are known as component developers & those who consume the controls are known as application developers or component consumers.

-While developing controls the developer should first design the control, write all the behavior to control, then define Properties, Methods & Events that are required for the control.

-Properties are defined to provide access to any values in the control to the application developer.
E.g.: Text property of TextBox, Checked property of CheckBox, etc.,


-Methods are defined so that any actions can be performed thru the controls whenever required.
E.g.: Clear(), Focus() methods of TextBox, Close() method of Form etc.,


Events: while developing control the developer of control may not know what actions have to be performed at some specific time periods.
Eg:
1. The developer of button control is not aware of what should happen when the end-user clicks on the button.

2. What should happen when the button is clicked by the end user will be decided by the application developer.
3. Even if decided by application developer it is the responsibility of the component developer to execute the code that is written by application developer whenever the end-user clicks on the button.
4. To resolve the above problem component developer first defines an event under his control and then asks the application developer to write code under an event procedure & bind it with the event he has defined so that whenever the event occurs or raises event procedure gets executed.
5. To execute the event procedures we are already aware that events will take the help of delegates.
Syntax to define Event:
[<modifiers>] event <delegate> <Name>


Note: As we are aware that events take the help of delegates to execute event procedures, so while defining events we must also specify which delegate will be used by the event to execute the event proc. So first a delegate has to be defined and then the event has to be defined.
E.g.:
public delegate void EventHandler(object sender, EventArgs e);
public event EventHandler Click;


-All delegates that are pre-defined in BCL which we are consuming right now under existing Controls Event's are declared with 2 parameters:
   1. object sender     2. EventArgs e


-This is the reason why all our event proc's are also taking the same two parameters b'coz we are already aware that IO params of the delegate should be same as the IO params of method it has to call.
Note: while defining events under our controls we can either make use of any pre-defined delegate or we can also define our own delegates.
Using pre-defined delegate under a new event:
             public event EventHandler MyClick;
-In this case, MyClick event proc takes 2 params b'coz EventHandler delegate is defined with 2 params.
  or
Using user-defined delegate under a new event:
          public delegate void MyEventHandler();
          public event MyEventHandler MyClick;
-In this case, MyClick event proc takes 0 params b'coz MyEventHandler delegate is defined with no params.


Note: if the delegate has any params' then only event proc's will have params or else event proc's will not have any params.
Tasks of Component Developer & App. Developer related to Events:
Component Developer Tasks:
1. Define a delegate (optional).
2. Define an event making use of a delegate (either pre-defined or user-defined).
3. Specify the time period when the event has to raise or occur.

Application Developer Tasks:
1. Define a event procedure.
2. Bind the event, delegate & event procedure with each other.

Note: for application developers, the above 2 tasks get performed implicitly when he double click on the event in the property window.

Declarations:
//Defining a delegate for using it under event:
public delegate void MyDelegate();
//Defining 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();
            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 have defined above
MyClick();

//Defining a property to access the elapsed time
public string ElapsedTime
{
  get { return mtbTime.Text; }
}

//Defining a method to start the StopClock
public void Start()
{
  btnStart.Enabled = false; 
  btnStop.Enabled = false;
  timer1.Start();
}


-Now open the solution explorer, right-click on the project, select build which compiles the project & generates an assembly ControlsProject.dll in the following location:
C:\CSharp5\ControlsProject\ControlsProject\bin\
Debug

Consuming the Stop Clock Control:
-Now open any our FormsProject, goto its ToolBox, right-click on it, select 'Add Tab', which adds a new tab in the ToolBox, name it as "My Controls".

-Now right click on the new tab we have added, select "Choose Items", which opens a dialog box "Choose ToolBox Items", click on Browse button in it and select the ControlsProject.dll assembly what we have created above from its physical location, which added the StopClock control under our tab.
-Now take a new Windows Form, add a StopClock control to it and test the behavior of control by running the form.
-Now to consume the properties, methods & events we have defined under the control do the following:

Consuming Property: add a new button on the form, set its text as "Show Elapsed Time" & under the click of the button write the following:
MessageBox.Show(stopClock1.ElapsedTime);


Consuming Method: now go to the load event of the form and write the following code under it, so that  StopClock starts implicitly when the form is loaded without clicking on Start button:
Under Load Event: stopClock1.Start();

Consuming Event: now go to Events of StopClock control where we will be finding the MyClick event we have defined, double click on it and write the following code under "stopClock1_MyClick" event procedure that gets executed when we click on the Close button of StopClock.
 this.Close();
Ex:

            using System;
            using System.Windows.Forms;
namespace ControlsProject
    {
        public class MyTextBox : TextBox
        {
            public enum Options
            {
                Any, Char, CharOrDigit, Digit
            };
            Options opt = 0;
            bool flag = false;
            public bool AcceptDecimal
            {
                get { return flag; }
                set { flag = value; }
            }
            public Options SetOption
            {
                get { return opt; }
                set { opt = 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 && Convert.ToInt32(e.KeyChar) != 32)
                        {
                            MessageBox.Show("Enter alphabets only");
                            e.Handled = true;
                        }
                        break;
                    case Options.CharOrDigit:
                        if (char.IsLetterOrDigit(e.KeyChar) == false)
                        {
                            MessageBox.Show("Enter alpha-numerics    only");
                            e.Handled = true;
                        }
                        break;
                }
            }
        }
    }

-Dock: It is a property available under all the controls which decide the location where the control sits on the container as well as the size of the control.

-It can be set with any of the following values:

  -Note: In this case, the size & location of the control will be the same as what we have specified while creating the control, that will not change in the runtime.
  
  -Left, Right, Top & Bottom: In this case, the control gets placed on any of the 4 chosen options with in the container and also adjusts itself according to the size of the container.

-Fill: In this case, the control occupies the complete available space of the container.

MessageBox:
Show(string msg)
Show(string msg, string caption)
Show(string msg, string caption, MessageBoxButtons buttons)
Show(string msg, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)

Under New MenuItem:

if (richTextBox1.Text.Trim().Length > 0)
            {
                DialogResult dr = MessageBox.Show(
                   "Do you wish to save the file?", "My Notepad", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                if (dr == DialogResult.Yes)
                {
                    DialogResult d = saveFileDialog1.ShowDialog();
                    if (dr != DialogResult.Cancel)
                    {
                        richTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);
                        richTextBox1.Clear();
                    }
                }
                else if (dr == DialogResult.No)
                    richTextBox1.Clear();
            }

Under Open MenuItem:
openFileDialog1.ShowDialog();
            richTextBox1.LoadFile(openFileDialog1.FileName, RichTextBoxStreamType.PlainText);
Under Save MenuItem:
DialogResult d = saveFileDialog1.ShowDialog();
            if (d != DialogResult.Cancel)
                richTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);
Under Exit MenuItem:
   this.Close();

Under Cut MenuItem:
   richTextBox1.Cut();

Under Copy MenuItem:
   richTextBox1.Copy();

Under Paste MenuItem:
   richTextBox1.Paste();

Under Select All MenuItem:
   richTextBox1.SelectAll();

Under WordWrap MenuItem:


            if (wordWrapToolStripMenuItem.Checked)
            {
                wordWrapToolStripMenuItem.Checked = false;
                richTextBox1.WordWrap = false;
            }
            else
            {
                wordWrapToolStripMenuItem.Checked = true;
                richTextBox1.WordWrap = true;
            }


Under Font MenuItem:
fontDialog1.ShowDialog();
richTextBox1.Font = fontDialog1.Font;

Under Color MenuItem:
colorDialog1.ShowDialog();
richTextBox1.ForeColor = colorDialog1.Color;


TreeView:
-It is a control used for representing the data in a hierarchical structure.
eg: Windows Explorer & Solution Explorer.

-Every element under the control is represented as nodes that can be either a parent or child.
-We can add nodes to the control in 2 ways:
 i) Manually using Tree Node Editor.
ii) Programmatically from Code Editor.

-To construct a tree manually go to properties of it, select Nodes property & click on the button beside it which opens Tree Node Editor. Use "Add Root" & "Add Child" buttons to add nodes in your required hierarchy.
-To assign a caption to the node make use of Text Property of the node.
-Call ExpandAll() method which displays nodes of the tree in an expanded state.
-The default event of TreeView is AfterSelect which fires when a node is selected under Tree. With-in the event we can identify the node that has been selected using "e.Node" property.
-Make use of Text property of the node to get the caption of node & make use of FullPath property to get a hierarchy of the node selected.
-Every Node under TreeView is recognized by its index position from the root node, as follows:
CEO  Nodes[0]
   -President 1 Nodes[0].Nodes[0]
      -Manager 1 Nodes[0].Nodes[0].Nodes[0]
   -President 2 Nodes[0].Nodes[1]
      -Manager 2 Nodes[0].Nodes[1].Nodes[0]
      -Manager 3 Nodes[0].Nodes[1].Nodes[1]

-To construct a tree programmatically make use of the method Nodes. Add of TreeView.
TreeView:
     Nodes.Add(string text)

Under Form Load:

            treeView1.Nodes.Add("CEO");
            treeView1.Nodes[0].Nodes.Add("Director1");
            treeView1.Nodes[0].Nodes[0].Nodes.Add("Manager1");
            treeView1.Nodes[0].Nodes.Add("Director2");
            treeView1.Nodes[0].Nodes[1].Nodes.Add("Manager2");
            treeView1.Nodes[0].Nodes[1].Nodes.Add("Manager3");
            treeView1.ExpandAll();

List View: it is used for displaying data in table format.
-To design a ListView first set View property of it as details, which gets the look of a table.
-To Add columns for ListView use Columns. Add method of it.
 Columns.Add(string name)
 Columns.Add(string name, int width)

-The first column of ListView is represented as item & identified by its index position, to add an item use Items. Add method of ListView.
 Items.Add(string text)

-From the second column of ListView, it is represented as subitem & identified by its index position, to add a SubItem under Item use SubItems.Add method of ListView referring to the Item under which we want to add.
 SubItems.Add(string text)

Note: while identifying a record from listview each cell can be referred to as a subitem (first also) with their index positions starting from 0.
-SelectedIndexChanged was the default event of ListView which gets raised when a record is selected as well as de-selected also.
-To get lines under ListView to make use of GridLines property by setting it as true.
-By default, the FullRowSelect property of ListView is disabled to enable set the property value as true.
Under Form Load:

            listView1.Columns.Add("Custid", 200);
            listView1.Columns.Add("Cname", 200);
            listView1.Columns.Add("City", 200);
            listView1.Columns.Add("Balance", 200);

            listView1.Items.Add("101");
            listView1.Items[0].SubItems.Add("Ajay");
            listView1.Items[0].SubItems.Add("Hyderabad");
            listView1.Items[0].SubItems.Add("10000");

            listView1.Items.Add("102");
            listView1.Items[1].SubItems.Add("Xyz");
            listView1.Items[1].SubItems.Add("Chennai");

            listView1.Items[1].SubItems.Add("14560");
 <--Add multiple records-->

Under SelectedIndexChanged:

if (listView1.SelectedItems.Count > 0)
            {
                MessageBox.Show(listView1.SelectedItems[0].SubItems[0].Text);
                MessageBox.Show(listView1.SelectedItems[0].SubItems[1].Text);
                MessageBox.Show(listView1.SelectedItems[0].SubItems[2].Text);
                MessageBox.Show(listView1.SelectedItems[0].SubItems[3].Text);

            }
SplitContainer: it is container control which contains 2 panels in it 1 in the LHS and 1 in the RHS, the sizes of these panels can be adjusted in the runtime.

            System.IO
   Directory.GetDirectories(string path) string[]
   Directory.GetFiles(string path) string[]

   File.ReadAllBytes(string path) byte[]
   File.GetLastWriteTime(string path) DateTime

String:
   Substring(int start)

   Substring(int start, int length)

-The substring method is used for picking a part of a string from a given string.

string str = "Hello"
str.Substring(2)  -> llo
str.Substring(0, 3) -> Hel
str.Substring(1, 3) -> ell

String:
   IndexOf(string s)
   IndexOf(string s, int start)
   LastIndexOf(string s)


-IndexOf & LastIndexOf methods are used for identifying the index position of a given string under the actual string.

string str = "Hello World";
str.IndexOf("W") -> 6
str.IndexOf("o") -> 4
str.IndexOf("o", 5) -> 7
str.LastIndexOf("o") -> 7

System.Diagnostics
   Process.Start(string <exename>)
-The start method under the Process class is capable of running any given exe.
eg:          Process.Start("calc.exe")
             Process.Start("C:\\CSharp11\\MyForm.exe");

Control:
-Text and Tag are 2 properties under control that can be used for associating user defined info with any control where Text is visible and Tag is not visible to the end-user, but both can be accessed by the programmers under the code.

using System.IO;
using System.Diagnostics;

Under Form Load:

treeView1.Nodes.Add("C:\\");
            string[] dirs = Directory.GetDirectories("C:");
            foreach (string dir in dirs)
            {
                string dpath = dir;
                string dname = dpath.Substring(2);
                treeView1.Nodes[0].Nodes.Add(dname);
            }
            treeView1.ExpandAll();
            listView1.Columns.Add("Name", 190);
            listView1.Columns.Add("Size", 75);
            listView1.Columns.Add("Type", 75);
            listView1.Columns.Add("Date Modified", 190);

Under TreeView AfterSelect:
            try
            {
                listView1.Items.Clear();
                string[] files = Directory.GetFiles(e.Node.FullPath);
                for (int i = 0; i < files.Length; i++)
                {
                    string fpath = files[i];
                    string fname = fpath.Substring(fpath.LastIndexOf("\\") + 1);
                    listView1.Items.Add(fname);
                    listView1.Items[i].Tag = fpath;
                    byte[] data = File.ReadAllBytes(fpath);
                    int size = data.Length / 1024;
                    size++;
                    listView1.Items[i].SubItems.Add(size + " kb");
                    listView1.Items[i].SubItems.Add("File");
                    DateTime dt = File.GetLastWriteTime(fpath);
                    listView1.Items[i].SubItems.Add(dt.ToString("g"));
                }
            }
            catch (Exception ex)
            { ex = null; }


Note: while converting a DateTime value into a string we can use for matters under the ToString method which can be either "D, d, T, t, G(d) or g".

Under ListView SelectedIndexChanged:
if (listView1.SelectedItems.Count > 0)
   Process.Start(listView1.SelectedItems[0].Tag.ToString());

CheckBox & RadioButton: both these controls are used so that the users can select from a list of available values.

-A CheckBox allows multiple selections whereas RadioButton allows only a single selection within a group of controls.
-While using RadioButtons under multiple options we will be facing a problem i.e as it allows only single selection at any point of time it will allow the only a single option to be selected, to overcome this we need to group related radio buttons.
-To group the radio buttons they need to be placed on separate containers like either a panel or group box controls.
-Both these controls provide u a boolean property known as Checked, which returns true if the controls are selected or else returns false.

Under Button1:
if (radioButton1.Checked)
                MessageBox.Show("Radio Button1 Selected");
            else if (radioButton2.Checked)
                MessageBox.Show("Radio Button2 Selected");
            else if (radioButton3.Checked)
                MessageBox.Show("Radio Button3 Selected");

 Under Button2:
   if (checkBox1.Checked)
                MessageBox.Show("Check Box1 Selected");
            if (checkBox2.Checked)
                MessageBox.Show("Check Box2 Selected");
            if (checkBox3.Checked)
                MessageBox.Show("Check Box3 Selected");

ComboBox, ListBox, CheckedListBox:
-These controls are used when we want the user to select from a list of available values.
-ComboBox allows only a single selection, whereas ListBox and CheckedListBox provide multi-selection.
-CheckedListBox is the same as a ListBox which displays a CheckBox beside each item to recognize the option that has been selected.
-ComboBox is editable whereas a ListBox and CheckedListBox are not.


-To add values under the control we have 4 different ways:
   i) Using the Items Collection property under the property window, to do this open property window corresponding to the control, select Items property and click on the button beside it which opens u a "String Collection Editor" window enter values under it, each in a new line.
 
  ii) Using the Items. Add method we can add Items under the control 1 at a time.
 <control>.Items.Add(object value)

 iii) Using the Items.AddRange method we can add an array of values at a time to the control.
              <control>.Items.AddRange(object[] values)

  iv) Using the DataSource property of the control we can bind a db table to the control, but we can display only a single column of the table within the control which has to be specified using the display member property.
 <control>.DataSource = <data table>
 <control>.DisplayMember = <col name>




-A ListBox by default allows only a single selection if u want to go for multi-selection we need to change the "Selection Mode" property of the control either to "MultiSimple" or "MultiExtended".
SelectionMode:
 -One (d)
 -None
 -MultiSimple (only mouse click)
 -MultiExtended (ctrl + mouse click)

-To identify the Item(s) that has been selected under the controls we can make use of the following properties:
 SelectedItem ComboBox, ListBox
 SelectedItems ListBox
 CheckedItems CheckedListBox
Under Show Selected Country:
MessageBox.Show(comboBox1.SelectedItem.ToString()); 

Under Show Selected States:
foreach (object obj in listBox1.SelectedItems)
   MessageBox.Show(obj.ToString());

Under Show Selected Colors:

string str = "";
            foreach (object obj in checkedListBox1.CheckedItems)
                str += obj.ToString() + ", ";
            str = str.Substring(0, str.Length - 2);
            MessageBox.Show(str);
Class Declarations:

              string[] q1 = { "January", "February", "March" };
            string[] q2 = { "April", "May", "June" };
            string[] q3 = { "July", "August", "September" };
            string[] q4 = { "October", "November", "December" };

Under ComboBox SelectedIndexChanged:
listBox2.Items.Clear();
            switch (comboBox2.SelectedIndex)
            {
                case 0:
                    listBox2.Items.AddRange(q1);
                    break;
                case 1:
                    listBox2.Items.AddRange(q2);
                    break;
                case 2:
                    listBox2.Items.AddRange(q3);
                    break;
                case 3:
                    listBox2.Items.AddRange(q4);
                    break;
            }

Panel, GroupBox, TabControl:
-All these 3 are containers that can be used for placing other controls over them.

-Panel and GroupBox are one and the same whereas a GroupBox has a caption but the panel doesn't have.
-A TabControl is a collection of pages that are arranged as pages in a book, where each page is referred to as TabPage.
-It provides links on top of the control known as Tab's to go to the required page.
-By default it comes with 2 TabPages, we can add a new page by right-clicking on the control & select "Add Tab" and delete by selecting "Remove Tab".
-This control is used in 2 situations like placing multiple controls on a form without vertical or horizontal scroll bars & grouping of related options by placing on separate TabPages.

PictureBox: it is used for displaying any image on the form.
-To load an image into the control we can use any of the following Properties:
     ImageLocation = "<path of the image>"
     Image = Image.FromFile("<path of the image>")

ToolTip:
-It is used for associating brief information about any control when the mouse is placed on the control.

Note: In classical VB & WPF (3.0) tooltip was property to every control, but in WinForms, it was a separate control again.
-SetToolTip is a method of the control that can be used for binding ToopTip to any of the control on form with a message.
   SetToolTip(Control ctrl, string msg)

Under Form Load:
   toolTip1.SetToolTip(button1, "Click Me");

Under Button Click:
openFileDialog1.ShowDialog();
pictureBox1.ImageLocation =       openFileDialog1.FileName;
toolTip2.SetToolTip(pictureBox1,      openFileDialog1.FileName); 

ErrorProvider:
-It is a control used for displaying error msgs under an application without a message box.
-To use the control first it has to be associated with a control for which the error has to be bound. To do this use the method SetError & Clear to remove the binding with control to which it was bound.

   SetError(Control ctrl, string errormsg)
   Clear()

Under TextBox Validating:

TextBox t = (TextBox)sender;
            if (t.Text.Trim().Length == 0)
            {
                errorProvider1.SetError(t, "Cannot leave emtpy");
                e.Cancel = true;
            }
            else
                errorProvider1.Clear();

Under Login Button:

if (textBox1.Text.Trim() == "Admin" && textBox2.Text.Trim() == "Admin")
                MessageBox.Show("Valid User");
            else
                MessageBox.Show("Invalid User");

Under Cancel Button:
   this.Close();

WebBrowser:
-It is used for displaying Html, Xml pages and Images within the windows applications.
   -Navigate(string path): it opens the specified file under the web browser.
   -GoBack()
   -GoForward()
   -Stop()
   -Refresh()
   -GoHome()
   -GoSearch()

-ToolStrip: it is a control used for creating ToolBars on your form.
-A ToolBar is similar to that of a MenuBar, whereas ToolBar can be placed with various controls like Buttons, Labels, TextBoxs, ComboBoxs, etc., on it.
-Every windows application has toolbars to it which can be multiple. eg: Visual Studio.
-To create a Toolbar to your application place a ToolStrip control on the form and then click on the LHS corner of the control which displays u the list of controls that can be added on it like Button, Label, TextBox, etc.,
-A control placed on the ToolBar is referred as a ToolStripControl i.e. ToolStripButton, ToolStripComboBox etc.,
-Once a Button is placed on the ToolStrip it looks like an Image with a default image set to it, it has a property DisplayStyle which can be used for changing the look of the control, the property can be set with values like None, Text, Image (d), Image & Text.
-To change the default image associated with it right click on the button and select SetImage which opens u a window click on the Import button and select an image from the hard disk.

-StatusStrip: It is a control that can be used for displaying status messages on the windows form eg: Browser.
-On this control also u can place controls similar to that of a toolstrip like StatusLabels, ComboBoxs, DropDownButtons, etc.,

Under Form Load:
   toolStripComboBox1.Focus();

Under Go Button:


   webBrowser1.Navigate(toolStripComboBox1.Text);
            if (toolStripComboBox1.FindStringExact(toolStripComboBox1.Text) == -1)
                toolStripComboBox1.Items.Add(toolStripComboBox1.Text);

            toolStripStatusLabel1.Text = "Done";
Under ComboBox KeyPress:
if (Convert.ToInt32(e.KeyChar) == 13)
   toolStripButton5.PerformClick();
Note: PerformClick is a method under the button class that executes the code under the click on the button when called.

Under ComboBox SelectedIndexChanged:
     toolStripButton5.PerformClick();

Under Open MenuItem:
openFileDialog1.ShowDialog();
toolStripComboBox1.Text = openFileDialog1.FileName;
toolStripButton5.PerformClick();

Under Close MenuItem:
   this.Close();

Under Back MenuItem:
   webBrowser1.GoBack();

Under Forward MenuItem:
   webBrowser1.GoForward();

Under Refresh MenuItem:
   webBrowser1.Refresh();

Under Stop MenuItem:
   webBrowser1.Stop();

User Controls:
-These are controls that were designed by us according to the requirements for reusability.

-These are of 2 types:
   -Controls created from scratch.
   -Inherited or Extended controls.

-Controls created from scratch in the sense here we are all together going to design the control according to our requirements.
-Inherited control in the sense here we are going to develop a new control by inheriting from an existing control and then provide additional functionalities:
eg: public class RichTextBox : TextBox
 public class MaskedTextBox : TextBox

-To develop user controls we are provided with the project template "Windows Forms Control Library" under which u can develop both types of controls.
-To develop a user control from scratch we need to create a class inheriting from the predefined class UserControl of System.Windows.Forms namespace.
MaskedTextBox: It's a control which can be used for taking the input from the user in some specific formats like phone number, credit card no, railway PNR no, etc.,
-To set a format to the control go to the properties of the control and select the property mask and click on the button beside it which opens u a "Input Mask Editor" under which u can select from any available formats like US Phone Number, Date, Time, etc or specify your own format by selecting the custom option and enter your format in the "Mask" Text Box below as following:
PNR Number: 000-0000000
Date & Time: 00/00/0000 00:00:00
Time:  00:00:00

Timer Control: It is a control that can be used for executing the code regularly on specified intervals, i.e. the code under a button executes only when the button is clicked whereas the code under the timer executes regularly once the specified time is elapsed once its starts execution.

-The control provides u the following properties, methods, and events:
Interval: A property to specify the elapsed time.
Tick: An event under which u need to write the code that has to be executed.
Start: A method using which we start the execution of the Timer.
Stop: A method using which we stop the execution of the Timer.


D:\CSharp7\CSharp7Controls\CSharp7Controls\bin\Debug\CSharp7Controls.dll

Developing Controls:
-As we are already aware that every control has Properties, Methods & Events. When we develop a control we can also define them under our controls.

-Whenever a control has some values which should be accessible outside of the control class we need to go for defining properties. eg: Text, Name, etc.,
-Define Methods under the control when u want to perform any actions with the control. eg: Clear(), Focus() etc., which were defined under the TextBox class.
-Define Events under the control when u want to specify a time period to perform certain actions. eg: Click is an event under the Button that performs an action when we press the button.
-How or When to define Events under a control? Ans. People working on controls were of 2 types:
 -Component Developer
 -Component Consumer
-Component Developer is the person who designs the controls that can be reused.
eg: Microsoft, who designed Button, Textbox, etc.,

-Component Consumer is one who uses the control that has been developed by the developer.
eg: Software Development companies (ourselves).

-A Component developer while developing a control never knows what action has to be performed when a button is pressed or a Form is opened etc.,
-The actions that have to be performed when the button is pressed or a Form is opened etc., has to be defined by the Consumer only, but the responsibility of executing the actions defined by the consumer has to be taken by the Developer only.
-Because these 2 people will never sit together to work at any point in time, they adopt a process to perform this task, i.e. a Developer first defines Events and Delegates under his control which is provided to the Consumer asking to write the code that has to be executed under an EventProcedure mapping with the Event of control, so whenever the Event raises the Delegate will take the responsibility of executing the code under the Procedure that is mapped with the event.
Syntax to define an event:
<modifiers> event <delegate> <event name>;
public event EventHandler Click;

Note: while defining an event u need to specify the name of the delegate which will execute the code.

Component Developer:

            public class Button
        {
            public delegate void EventHandler(object sender, EventArgs e);
            public event EventHandler Click;
        }

Component Consumer:


     public class Form1 : Form
        {
            public Form1()
            {
                Button b = new Button();
                b.Text = "Click Me";
                b.Click += new EventHandler(Test);
                this.Controls.Add(b);
            }
            private void Test(object sender, EventArgs e)
            {
                Console.WriteLine("Event Raised");
            }
            static void Main()
            {
                Application.Run(new Form1());
            }
        }

Note: After defining an event under the controls the developer also needs to specify when this event has to be raised.

-Passing parameters to a delegate are optional, whereas Microsoft followed a convention while defining delegates i.e. every delegate takes 2 parameters "sender & e" so the mapping event procedures should also take them.
-When we were defining a delegate if no input params were specified the Event Procedure also doesn't require any parameters.

Class Declarations:
   //Defining a delegate to execute the Event
   public delegate void MyEventHandler();
   //Defining an event for the control
   public event MyEventHandler MyClick;
   int min = 0, sec = 0;
   string minstr, secstr;  

Under Load Event:
   maskedTextBox1.Text = "0000";

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();
            maskedTextBox1.Text = minstr + secstr;


Under Start Button:    timer1.Start();

Under Stop Button:
   timer1.Stop();

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

//Defining a property to access the stopcock's time
public string ShowTime
{
   get { return maskedTextBox1.Text; }
}

//Defining a method to start the StopClock
public void StartClock()
{
   timer1.Start();
}

Under Close Button:
   //Raising the MyClick event defined by us:
   MyClick();

-Now open the solution explorer right click on the project and select build which compiles the project and creates an assembly under the following location:

C:\CSharp7\ControlsProject\ControlsProject\bin\Debug\


Under Form Load:
   //Calling the method defined under StopClock
   stopClock1.StartClock();

Under Button Click:
   //Calling the property defined under StopClock
   MessageBox.Show(stopClock1.GetTime);           

Under stopClock1_MyClick:
   MessageBox.Show("Event Raised");           


  using System;
            using System.Windows.Forms;
namespace CSharp11Controls
    {
        public class MyTextBox : TextBox
        {
            public enum Options { Any, Chars, CharOrDigits, Digits }
            Options opt = 0;
            public Options SetOption
            {
                get { return opt; }
                set { opt = 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.Digits:
                        if (char.IsDigit(e.KeyChar) == false)
                        {
                            MessageBox.Show("Enter numerics only");
                            e.Handled = true;
                        }
                        break;
                    case Options.Chars:
                        if (char.IsLetter(e.KeyChar) == false)
                        {
                            MessageBox.Show("Enter characters only");
                            e.Handled = true;
                        }
                        break;
                    case Options.CharOrDigits:
                        if (char.IsLetterOrDigit(e.KeyChar) == false)
                        {
                            MessageBox.Show("Enter alphanumerics only");
                            e.Handled = true;
                        }
                        break;
                }
            }

No comments: