Tuesday 10 December 2013

Windows Application Concepts


Windows Forms Applications using C#.NET
  •  It is a GUI (Graphical User Interface) application that runs on Windows o/s
  •  A Windows Forms Application (Windows Application) is a collection of forms.                            
  • Ex:  Notepad, WordPad, Paint, MS Word etc.
Form:
·         It is a graphics container, using which we can draw some graphics +  we can place some graphical controls such as labels, text boxes, buttons etc.

Steps for creating a form:
    1) Open vs 2010 or 2012
    2) File - New - Project
    3) Visual C# - Windows Forms Application.
    4) Project Name:  WinApp1
    5) Location = D:\
    6) Ok
Properties of Form:
   These are used change visual appearance of the form

1.      Text: used to change title of the form.
            Ex: Text = Welcome
2.      BackColor: used to specify background color of the form.
              Ex: BackColor = HotPink
3.      Size: used to specify width and height of the form.
              Ex: Size
                     Width = 500 (pixels)
                     Height = 200 (pixels)
4.      BackgroundImage:
it is used to applya background image for the form.
              Ex: BackgroundImage = sample.jpg
5.      BackgroundImageLayout:
it is used to specify tile / stretch of the background image.
            Ex: BackgroundImageLayout = Tile
6.      Cursor: it is used to specify mouse pointer while working in the form.
            Ex: Cursor = Hand
7.      Icon: it is used to specify icon file path.
            Ex: Icon = sample.ico
8.      ShowIcon: it is used to show / hide the icon of the form.
            Ex: ShowIcon = false
9.      ShowInTaskbar:  it is used to show / hide the form title in the windows taskbar.
            Ex:  ShowInTaskbar = false
10.  MinimizeBox:  it is used to show / hide the 'minimize box' of the form.
            Ex: MinimizeBox = false
11.  MaximizeBox:  it is used to show / hide the 'maximize box' of the form.
            Ex:  MaximizeBox = false
Note: if you specify 'MinimizeBox = false' and also 'MaximizeBox = false' at-a-time, both will be hidden.
12.  HelpButton:  it is used to show / hide the 'help button' (?) on the form.
            rule: MinimizeBox = false and MaximizeBox = false
13.  Opacity:  it is used to make the form transparent.
            Ex:  Opacity = 0% to 100%
14.  ControlBox:  it is used to show / hide the control box (minimize box + maximize box + close box) for the form.
            Ex:  ControlBox = false
15.  AutoScroll: it is used to show / hide the scroll bars on the form. this is useful when there some controls on the foirm.
            Ex: AutoScroll = true
16.  FormBorderStyle: it is used to specify whether the form is re-sizable at run time, or not.
            Options:  None / FixedSingle / Fixed3D / Sizable / FixedToolWindow / SizableToolWindow
17.  WindowState: it is used to identify / change current window status of the form, whether it is minimized / maximized.
            Options:  Normal / Minimized / Maximized
Event Driven Programming
·         In GUI applications, code execution flow is different from 'console apps'.
·         So GUI apps code execution is called as 'Event Driven Programming'.
·         Event: is an action that is performed by user at run time.
·         Ex:  When a door bell is pressed, sound is played.
                                   Here 'Press' is the event.
·         An event will its associated function, in which we can write any code.
Form events:
    These are the events (actions), done by the user, based on the form.
1.      Load:  it executes when the form runs (form loads into memory).
2.      Click:  it executes when the user clicks anywhere on the form.
3.      DoubleClick:  it executes when the user double clicks the form.
4.      Move:  it executes when the user moves the form at run time.
5.      Resize:  it executes when the resizes the form at run time.
6.      KeyPress:  it exeutes on pressing any key on the keyboard.
7.      Scroll:  it executes on scrolling the form at run time.
8.      FormClosing:  it executes on closing the form.
Ex:-
Develop a c# win app, to demonstrate the form events.
Steps:
·         Create a new c# win app.
            Project Name = FormEventsDemo
·         It shows 'Form1' automatically.
·         Go to properties window.
            (Right click on the form and say 'Properties')
·         Properties of Form1:
            Name = Form1
            BackColor = SkyBlue
·         Click on 'Events' icon in the properties window.
·         Double click on 'Load' event:
        private void MyForm_Load(object sender, EventArgs e)
        {
            MessageBox.Show("Welcome");
        }
·         Double click on 'Click' event:
        private void MyForm_Click(object sender, EventArgs e)
        {
            MessageBox.Show("You clicked the form at " + DateTime.Now.ToString());
        }
·         Double click on 'FormClosing' event:
        private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            MessageBox.Show("Good bye");
        }
Changing form properties dynamically at run time:

  Ex: this.Text = "hello";
 These are used to change properties of the form, based on the user's requirement, through code.
·         Changing 'Text' property:
            Syntax:  this.Text = "some string here";
            Ex app:   Show good morning / good afternoon / Good evening message in the form's title bar, based on system time.
Note: When we double click on the form at design time, it generates code for 'Load' event.  Bcoz, 'Load' is the default event of the form.
·         Changing 'BackColor' property
            Syn:  this.BackColor = Color.yourcolorname;
            Ex App:  Develop a win app, which changes to darkgreen color when you double click it.
·         Changing 'BackgroundImage' property at run time:
            Syn:   this.BackgroundImage = Image.FromFile("file path here");
            Ex App:   show a background image, when the user press any key.
Working with WinForms Controls:-
·         A control is a GUI component, which can be displayed on a windows form.
·         Ex: Label, Button, TextBox etc.
·         C# recognizes each as a 'class'.
·         All the control classes are present under a namespace called 'System.Windows.Forms'.
                System.Windows.Forms
                       - Label
                       - Button
                       - TextBox
·         When you drag and drop a control from the Toolbox into the form, system automatically creates an object for the corresponding class.
Label
·         It is used to show a fixed message on the screen.
·         It is useful for showing:
            a) Titles
            b) Prompting text
            c) Description
 Properties of Label
·         Name: Used to specify programmatic name of the label.
o   Ex: Name = Label1
·         Text: Used to specify actual text of the label.
o   Ex: Text = Hello
·         BackColor: Used to specify background color of the label.
o   Ex: BackColor:  Green
·         ForeColor: Used to specify foreground color (text color) of the label.
o   Ex: ForeColor = Yellow
·         Font: Used to specify font settings of label such as font name, bold, italic, underline etc.
o   Ex: Arial, 30
·         Location: Used to specify position of the label on the foirm. It specifies X and Y co-ordinates.
o   Ex: Location
-          X = 300
-          Y = 200
·         AutoSize: Used to enable / disable automatic sizing for the label.
o   Ex: AutoSize = false
Events of Label
·         Click: Executes when you click on the label.
·         DoubleClick: Executes when you double click on the label.
·         MouseEnter: executes when you place mouse pointer over the label.
·         MouseLeave: executes when you move the mouse pointer outside the label.
Ex:-
Develop a c# win forms app, to show system date & time, when you click it.
Steps:
·         Create a new c# win form app.
o   Project Name = LabelDemo
·         Place 3 labels from tool box into the form.
·         Properties of Label1:
Ø  Font = Berlin Sans FB Demi, 30
Ø  Text = Welcome
Ø  ForeColor = DarkRed
·         Properties of Label2:
Ø  Font = Candara, 20
Ø  BackColor = DarkGreen
Ø  ForeColor = Yellow
·         Properties of Label3:
Ø  Font = Trebuchet MS, 14
Ø  AutoSize = false
Ø  Text = Click label2 to get system date and time
·         The form looks as shown below.
Code:
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 LabelDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void label2_Click(object sender, EventArgs e)
        {
            label2.Text = DateTime.Now.ToString();
        }
    }
}
 Button:-
·         It is used to display a clickable command button on the for the user, and also execute some code when the user clicks it.
·         Ex: OK, Cancel etc.
Properties of Button:
·         Name, Text, BackColor, ForeColor, Font, Location, Size
·         Image: used to specify an icon image in button.
·         ImageAlign: specifies position of the image in the button.
·         TextAlign: specifies position on the text in the button.
Events of Button:
·         Click, MouseEnter, MouseLeave
Ex:-
Develop a c# win app, which contains Save & Exit buttons.
Steps:
·         Create a new c# win app.
o   Project Name = ButtonDemo
·         It shows Form1 automatically.
·         Place two buttons.
·         Properties of Button1:
§  Text = Save
§  Image = save.png
§  ImageAlign = MiddleLeft
§  TextAlign = MiddleRight
·         Properties of Button2:
§  Text = Exit
§  BackColor = DarkRed
§  ForeColor = Cyan
·         The form looks like this:
Code:-
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 ButtonDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //Code:
        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Saved!");
        }

        private void button2_MouseEnter(object sender, EventArgs e)
        {
            button2.BackColor = Color.Cyan;
            button2.ForeColor = Color.DarkRed;
        }

        private void button2_MouseLeave(object sender, EventArgs e)
        {
            button2.BackColor = Color.DarkRed;
            button2.ForeColor = Color.Cyan;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close(); //closes the current working form
        }
    }
}
PictureBox:-
·         It is used to show an image on the form at desired place.
Properties of PictureBox:
·         Name, Image, Size, Location
·         SizeMode = Center / Stretch etc.
 Events of PictureBox:
·         Click, DoubleClick, MouseEnter, MouseLeave
Ex:-
Develop a win app, which shows an image, based on the selection.
  Steps:
·         Create a new c# win forms app.
o   Name = PictureBoxDemo
·         Drag & drop 7 buttons, 1 PictureBox on the form.
·         Properties of Button1:
o   Text = Small
·         Properties of Button2:
o   Text = Medium
·         Properties of Button3:
o   Text = Large
·         Properties of Button4:
o   Text = image 1
·         Properties of Button5:
o   Text = image 2
·         Properties of Button6:
o   Text = image 3
·         Properties of Button7:
o   Text = image 4
·         Properties of PictureBox1:
o   SizeMode = Zoom
o   Image = img1.jpg
·         Properties of Form1:
o   Text = Image Viewer
o   WindowState = Maximized
·         The form looks like this:
Code:-
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 PictureBoxDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //Code:

        private void button1_Click(object sender, EventArgs e)
        {
            pictureBox1.Size = new Size(100, 100);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            pictureBox1.Size = new Size(200, 200);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            pictureBox1.Size = new Size(300, 300);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            pictureBox1.Image = Image.FromFile(@"E:\Harsha\Images\WallPapers\img1.jpg");
        }

        private void button5_Click(object sender, EventArgs e)
        {
            pictureBox1.Image = Image.FromFile(@"E:\Harsha\Images\WallPapers\img2.jpg");
        }

        private void button6_Click(object sender, EventArgs e)
        {
            pictureBox1.Image = Image.FromFile(@"E:\Harsha\Images\WallPapers\img3.jpg");
        }

        private void button7_Click(object sender, EventArgs e)
        {
            pictureBox1.Image = Image.FromFile(@"E:\Harsha\Images\WallPapers\img4.jpg");
        }


    }
}

TextBox:-
·         It is used to accept a string value from keyboard.
·         Types of text boxes:
            a) Single line text box (default)
            b) Multi line Text box
            c) Password text box
Properties of TextBox:
·         Name, Text, BackColor, ForeColor, Size, Location, Cursor
·         MaxLength: Used to specify maximum no. of chars that can be typed in the text box.
o   Ex: MaxLength = 30
·         PasswordChar: used to specify char of password.
o   Ex: PasswordChar = *
·         Multiline: true / false
o   It is used to make the text as multi line text box.
o   Ex:  MultiLine = true
·         ScrollBars = None / Horizontal / Vertical / Both
o   It is used to show scroll bars with in the multi line text box.
·         ReadOnly = true / false
o   It is used to make the text box, read-only.
o   Ex:  ReadOnly = true
·         Enabled = true / false
o   It is used to enable / disable the text box. when you disable the text box, its events will not be executed.
o   Ex: Enabled = false
·         Visible = true / false
o   It is used to show / hide the text box.
o   Ex: Visible = false
·         TabIndex:  It is used to specify tab order of the text boxes. you must provide an incremental for the tab index.
Events of TextBox:
·         Click, DoubleClick, MouseEnter, MouseLeave
·         TextChanged:  it executes on changing text value at run time. that means it executes on typing / erasing the text at run time.
·         KeyPress: it executes on pressing any key on the board, while working in the text box. using we can also block required chars not be typed in the text box.
Ex:-
Develop a simple c# win form app, which shows 'hi' message to user.
 Steps:
·         Create a new c# win app.
o   Project Name = TextBoxDemo1
·         Design the form as shown below.
Code:-
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 TextBoxDemo1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //Code
        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Hi, " + textBox1.Text + " " + textBox2.Text);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }
}

Ex:-
Develop a registration form using c# win forms.
  Steps:
·         Design a form as shown below.
·         Properties of TextBox1:
-          Name = txtStudentName
-          MaxLength = 30
·         Properties of TextBox2:
-          Name = txtAge
-          MaxLength = 2
·         Properties of TextBox3:
-          Name = txtPassword
-          MaxLength = 30
-          PasswordChar = *
·         Properties of TextBox4:
-          Name = txtRetypePassword
-          MaxLength = 30
-          PasswordChar = *
·         Properties of TextBox5:
-          Name = txtAddress
-          Multiline = true
-          Scrollbars = Vertical
·         Properties of TextBox6:
-          Name = txtQualification
·         Properties of TextBox7:
-          Name = txtCourseName
-          Text = .NET
-          ReadOnly = true
·         Properties of TextBox8:
-          Text = PEERS
-          Enabled = false
·         Design the form as shown 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 TextBoxDemo2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //declare the variables
            string StudentName;
            int Age;
            string Password, RetypePassword, Address, Qualification, CourseName, InstituteName;

            //read values from controls
            StudentName = txtStudentName.Text;
            Age = Convert.ToInt32(txtAge.Text);
            Password = txtPassword.Text;
            RetypePassword = txtRetypePassword.Text;
            Address = txtAddress.Text;
            Qualification = txtQualification.Text;
            CourseName = txtCourseName.Text;
            InstituteName = txtInstituteName.Text;

            //show message
            string msg = "";
            msg += "Your registration accepted!";
            msg += "\nStudent Name: " + StudentName;
            msg += "\nAge: " + Age;
            msg += "\nPassword: " + Password;
            msg += "\nRe-type Password: " + RetypePassword;
            msg += "\nAddress: " + Address;
            msg += "\nQualification: " + Qualification;
            msg += "\nCourse Name: " + CourseName;
            msg += "\nInstitute Name: " + InstituteName;

            MessageBox.Show(msg);
        }
    }
}

Working with "Auto Complete" feature in Text Box:
·         It shows the list of matching items, while typing the text in the TextBox.
·         It is of two types:
            a) Auto-List from hard disk file system
            b) Auto-List from a user defined collection
a) Auto-List from hard disk File system:
·         It shows list of file names & folder names automatically.
·         Properties of TextBox:
Ø  AutoCompleteMode = Suggest
Ø  AutoCompleteSource = FileSystem
b) Auto-List from a user defined collection:
·         It shows list of items when you type atleast 1 char in the text box.
·         Properties of TextBox:
Ø  AutoCompleteMode = Suggest
Ø  AutoCompleteSource = CustomSource
Ø  AutoCompleteCustomSource = item 1
                                                                item 2
                                                                 .....
Ex:-
Demo on 'AutoComplete':
·         Create a new c# win app, and place 3 labels and 3 text boxes.
·         Properties of TextBox1:
-          AutoCompleteMode = Suggest
-          AutoCompleteSource = FileSystem
·         Properties of TextBox2:
-          AutoCompleteMode = Suggest
-          AutoCompleteSource = FileSystemDirectories
·         Properties of TextBox3:
-          AutoCompleteMode = Suggest
-          AutoCompleteSource = CustomSource
-          AutoCompleteCustomSource = Uttar Pradesh
               Maharashtra
               .....
Working with 'TextChanged' event of TextBox:
·         This event executes, when the user types / erases any text in the textbox, at run time.

Ex:-
Develop a c# win app, to show net price automatically, based on the actual product price, discount = 10% on product price
Steps:
·         Create a new c# win app.
·         Project Name = TextChangedEventDemo
·         Design form1 as shown below.
Code:
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 TextChangedEventDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //code:
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            //get current value of textbox1
            string str = textBox1.Text;
            if (str == "")
            {
                label4.Text = "Unknown";
                label5.Text = "Unknown";
            }
            else
            {
                double Price = Convert.ToDouble(textBox1.Text);
                double Discount = Price * 10 / 100;
                double NetPrice = Price - Discount;

                //show output in labels
                label4.Text = Convert.ToString(Discount);
                label5.Text = Convert.ToString(NetPrice);
            }
        }
    }
}
Working with 'KeyPress' event of text box:
·         This event executes when the user press any key on the keyboard, while workinbg in the text box.
·         This event may also be used to prevent typing un-expected chars in a textbox.
Steps:
·         Create a new c# win app, which accepts alphabets only in TextBox1 & 2;   numbers only in TextBox3.

Code:
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 KeyPressEventDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //Code
        private bool CheckAlphabet(char ch)
        {
            char[] AllowedChars = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' ', '\b' };
            if (Array.IndexOf(AllowedChars, ch) >= 0)
                return (false); //accept it
            else
                return (true); //reject it
        }

        private bool CheckNumber(char ch)
        {
            if (ch == '1' || ch == '2' || ch == '3' || ch == '4' || ch == '5' || ch == '6' || ch == '7' || ch == '8' || ch == '9' || ch == '0')
                return false; //accept it
            else
                return true; //reject it
        }

        private void txtFirstName_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = this.CheckAlphabet(e.KeyChar);
        }

        private void txtLastName_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = this.CheckAlphabet(e.KeyChar);
        }

        private void txtAge_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = this.CheckNumber(e.KeyChar);
        }
    }
}

Container Controls:-
·         These are used to contain various other controls inside.
·         C# supports two types of containers
            1) Form (Outer container)
            2) Sub container
·         Sub containers are used to divide the form as no. of units.
·         Sub Containers (Container Controls) in c#:
            1) Panel
            2) GroupBox
            3) TabControl
            4) FlowLayoutPanel
Panel:-
·         It is a sub container, in which you can place any controls.
·         It allows its inner controls to be located based X and Y co ordinates.
Properties of Panel:
·         BackColor, ForeColor, Font, BackgroundImage, Size, Location, Cursor etc.
Events of Panel:
·         MouseMove, MouseEnter, MouseLeave etc.
Ex:-
Demo on mouse move?
Code:
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 PanelDemo1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //code
        private void panel1_MouseMove(object sender, MouseEventArgs e)
        {
            label1.Text = e.X + ", " + e.Y;
        }
        //note: 'EventArgs e' is a small variable, that is available in every event handler, which provides additional info about current action.
    }
}
GroupBox:
·         It is same as Panel, but can show a title also.
·         Properties of GroupBox:
·         Text, BackColor, ForeColor, Font, BackgroundImage, Size, Location, Cursor etc.
·         Events of GroupBox:
·         MouseMove, MouseEnter, MouseLeave etc.
TabControl:
·         It is used to show any one tab to the user.
·         TabControl is a collection of 'tab pages'.
Steps for development of TabControl:
·         Drag & drop TabControl into the form.
·         Note: by default, it creates two tab pages.
·         Select 'TabControl1' and goto 'TabPages' property
In this property, we can add / remove the pages.
·         Place controls directly in the tab pages.
Ex:-
Develop a c# win app, which shows 'user profile'.
·         Design the form as shown below:

FlowLayoutPanel:
·         It is used to 'automatically arrange' the controls in an relative order.
Ex:-
Develop a 'PhotoGallery' app, using 'FlowLayoutPanel'.
Steps:
·         Create a new c# win app.
·         Drag & drop 'FlowLayoutPanel' from Toolbox into the form.
·         Drag & drop 9 picture boxes into 'flowlayoutpanel'.
·         Set 'Image' property of all picture boxes.
·         Set 'SizeMode = Stretch' for all picture boxes.
·         Properties of 'FlowLayoutPanel1':
            BackColor = { any color }
            AutoScroll = true
Dynamic Creation of Controls:- (or)
Creating Controls at run time:-
·         It is used to generate controls dyanamically at run time.
·         Controls can be created in two ways:
            a) Static Control Creation
            b) Dynamic Control Creation
a) Static Control Creation
·         Drag & drop the controls from Toolbox.
·         Easy to create
·         This is good if the developer knows, how many controls he wants.
b) Dynamic Control Creation
·         Create control objects thru code (programmatically).
·         A bit difficult
·         This is good if the developer dont know, how many controls he wants.
Steps for dynamic controls creation:
·         Create an object for the control class.
Ø  Label L1 = new Label();
·         Add necessary properties to the object:
Ø  L1.Text = "some text";
Ø  L1.Font = new Font("font name", size);
Ø  L1.Location = new Point(x, y);
Ø  L1.Size = new Size(width, height);
Ø  L1.BackColor = Color.colorname;
Ø  L1.ForeColor = Color.colorname;
Ø  etc.
·         Handle the events:
Ø  L1.Click = new System.EventHandler(L1_Click);
·         Add controls to the container:
Ø  this.Controls.Add(L1);
                                (or)
Ø  flowLayoutPanel1.Controls.Add(L1);
Ex:-
Develop an app, which produces 'n' text boxes at run time.
Steps:
·         Create a new c# win app.
Ø  Project Name: DynamicControlsCreationDemo
·         Drag & drop 1 label, 4 buttons, 1 flowlayoutpanel, 1 more button.
·         Properties of label1:
Ø  Text = How many friends you have
·         Properties of button1:
Ø  Text = 5
·         Properties of button2:
Ø  Text = 10
·         Properties of button3:
Ø  Text = 20
·         Properties of button4:
Ø  Text = 30
·         Properties of FlowLayoutPanel1:
Ø  BackColor = {any color}
Ø  AutoScroll = true
·         Properties of button5:
Ø  Text = OK
Code:

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 DynamicControlsCreationDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //Code:

        //user-defined method
        private void GenerateTextBoxes(int n)
        {
            flowLayoutPanel1.Controls.Clear();

            for (int i = 1; i <= n; i++)
            {
                //step 1: create an object the control class
                TextBox txt = new TextBox();

                //step 2: set necessary prop
                txt.Name = "TextBox" + i;
                txt.BackColor = Color.Aqua;

                //step 3: add text box to the container
                flowLayoutPanel1.Controls.Add(txt);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.GenerateTextBoxes(5);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.GenerateTextBoxes(10);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.GenerateTextBoxes(20);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            this.GenerateTextBoxes(30);
        }

        private void button5_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < flowLayoutPanel1.Controls.Count; i++)
            {
                TextBox txt = (TextBox)flowLayoutPanel1.Controls[i];
                string s = txt.Text;
                MessageBox.Show(s);
            }
        }
    }
}



Working with 'Menus' in win forms:
·         Menu:  it is a collection of options.
·         Two types of menus:
Ø  MenuStrip
Ø  ContextMenuStrip
MenuStrip:-
·         Used to create menu bars.
·         Ex:   File   Edit   View
ContextMenuStrip:
·         Used to create 'right click menus'.
Steps for working with 'MenuStrip':
·         Drag & drop 'MenuStrip' control from Toolbox into the form.
Ø  Toolbox > Menus & Toolbars > MenuStrip
·         Design menu items in menu strip, by clicking on 'Type here' message.
·         Handle 'Click' events for all menu items (menu options).
·         Run the app, and click on the menu item.
Ex:-
Develop a c# win app, with following menu.
BackgroundColor
BackgroundImage
Window
Exit
Light Yellow
Sunset
Normal

Pink
Water lilies
Minimize

Chocolate
None
Maximize

Blue




               
                             
Code:                                 
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 MenuStripDemo2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        //Code
        private void lightYellowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.BackColor = Color.LightYellow;
        }

        private void pinkToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.BackColor = Color.Pink;
        }

        private void chocolateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.BackColor = Color.Chocolate;
        }

        private void blueToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.BackColor = Color.Blue;
        }

        private void sunsetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.BackgroundImage = Image.FromFile(@"C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Sunset.jpg");
            sunsetToolStripMenuItem.Checked = true;
            waterLiliesToolStripMenuItem.Checked = false;
            noneToolStripMenuItem.Checked = false;
        }

        private void waterLiliesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.BackgroundImage = Image.FromFile(@"C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Water lilies.jpg");
            waterLiliesToolStripMenuItem.Checked = true;
            sunsetToolStripMenuItem.Checked = false;
            noneToolStripMenuItem.Checked = false;
        }

        private void noneToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.BackgroundImage = null;
            noneToolStripMenuItem.Checked = true;
            sunsetToolStripMenuItem.Checked = false;
            waterLiliesToolStripMenuItem.Checked = false;
        }

        private void normalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
        }

        private void minimizeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void maximizeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show(
                "Are you sure to close?",
                "Peers",
                MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                //code for yes
                //system will automatically closes the form
            }
            else
            {
                //code for no
                e.Cancel = true; //stops closing the form
            }
        }
    }
}
ContextMenuStrip:
·         It is used to create 'right click menus'
Steps for working with 'Context menu Strip':
·         Drag & drop 'ContextMenuStrip' control from toolbox.
·         Create menu items in 'ContextMenuStrip'
·         Set the property of required control (or) form
Ø  ContextMenuStrip = { name of your context menu strip }
·         Handle click events of each menu item.
·         Run the app, right on the required control (or) form & click on the menu item.
ToolStrip:
·         It is used to create tool bars.
·         A tool bar is a collection of 'tool bar buttons'.
Steps for working with 'ToolStrip':
·         Drag & drop 'ToolStrip' control from toolbox.
Ø  Toolbox > Menus&Toolbars > ToolStrip
·         Go to 'Items' property of 'ToolStrip' and add required buttons.
·         Double click on each toolbar button and handle the 'Click' event.
ImageList:
·         It is a collection of few images.
·         It is used to apply images to 'menu items' (or) tool bar buttons.
Ex:-
Demo on contextmenu, imagelist, toolstrip
·         Properties of TextBox1:
Ø  ContextMenuStrip = ContextMenuStrip1
Code:
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 ContextMenuStripDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            //any code
        }


        //code:
        private void cutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            textBox1.Cut();
        }

        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            textBox1.Copy();
        }

        private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            textBox1.Paste();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //applies source of the images to context menu strip
            contextMenuStrip1.ImageList = imageList1;

            //apply image index to the menu items
            cutToolStripMenuItem.ImageIndex = 0;
            copyToolStripMenuItem.ImageIndex = 1;
            pasteToolStripMenuItem.ImageIndex = 2;

            //apply source of the images to toolstrip1
            toolStrip1.ImageList = imageList1;

            //apply image index to the tool bar buttons
            toolStripButton1.ImageIndex = 0;
            toolStripButton2.ImageIndex = 1;
            toolStripButton3.ImageIndex = 2;
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            textBox1.Cut();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            textBox1.Copy();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            textBox1.Paste();
        }
    }
}
Programming Model of a form:
·         C# recognizes each form as a class.
·         Generally a class contains 3 types of members:
·         Data members:
Ø  All the controls that are placed within the form.
·         Properties:
Ø  Text, Backcolor, WindowState etc.
·         Methods:
Ø  Event handlers
Ø  User-defined methods
Rules a form class:
·         A form class must be a partial class.
            public  partial  class Form1 : Form
            {
            }
·         Observation:  for every form, visual studio generates 2 files automatically.
            Ex:  Form1.cs
                   Form1.Designer.cs
·         Form1.cs:  contains user-defined code of the form, like event handlers & user-defined methods.
·         Form1.Designer.cs:  contains system-generated code (designer code)
·         Every form must be a child class of 'System.Windows.Forms.Form' class
Ø  It provides designer winow + form properties + form events to the child class.
·         Every form should contain a constructor, with InitializeComponent() method.
Ø  It internally calls the system defined code.
Code execution sequence of the form:
·         System allocates some memory for the form object.
·         Constructor
·         Form1_Load()
·         Other event handlers, based on the action done by user,
Ø  ex: button1_Click
·         Form1_FormClosing


Working with 'Popup windows' in Win forms:
·         These are used to open another form when you click on a button in the first form.
Steps:
·         Add form to the project:
Ø  Solution Explorer > Right click on the project name > Add -> New Item -> Windows Form -> Name = Form2.cs -> Add.
·         Create an object for 'Form2' class:
Ø  Form2  f = new Form2();
·         Show it:
Ø  f.ShowDialog();
·         Pass any data to the form (optional):
Ø  f.Tag = value;
Ex:-
Develop a c# win form app, which shows 'hello' message to the user, in popup window.
Steps:
·         Create a new c# win app
Ø  Project Name = PopupWindowDemo
·         Add 'Form2' to the project.
·         Design form1 as shown below
       
·         Design form2 as shown below
Code for form1:
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 PopupWindowsDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //Code in 'Form1':

        private void button1_Click(object sender, EventArgs e)
        {
            //create an object for Form2
            Form2 f2 = new Form2();

            //add data to f2
            //f2.Tag = textBox1.Text;
            Class1 c1 = new Class1();
            c1.a = 10;
            c1.b = 20;
            f2.Tag = c1;


            //show f2
            f2.ShowDialog();
        }
    }
}

Code for form2:
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 PopupWindowsDemo
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        //code in 'Form2':

        private void Form2_Load(object sender, EventArgs e)
        {
            //label1.Text = "Welcome, " + Convert.ToString(this.Tag);
            //this.Text = "Welcome, " + Convert.ToString(this.Tag);

            Class1 c1 = (Class1)this.Tag;
            MessageBox.Show(c1.a.ToString());
            MessageBox.Show(c1.b.ToString());
        }
    }
}
'ErrorProvider' control in WinForms:
·         It is used to validate the input fields, whether they are correctly entered or not.
Ex:-
Demo on ‘Errorprovider’ control
·         Design form1 as shown below
Code:
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 ErrorProviderDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        //double click on 'Leave' event of TextBox1
        private void textBox1_Leave(object sender, EventArgs e)
        {
            //get email from text box
            string Email = textBox1.Text;

            //check
            if (Email.IndexOf(" ") == -1 &&
                (Email.EndsWith(".com") || Email.EndsWith(".co.in")) &&
                Email.IndexOf("@") > 0)
                errorProvider1.SetError(textBox1, ""); //no error msg
            else
                errorProvider1.SetError(textBox1, "Invalid e-mail"); //show message
        }
    }
}

No comments:

Post a Comment