Anda di halaman 1dari 52

Controls

Link lable controls


LinkLabel l1=new LinkLabel(); Controls.Add(l1); l1.Name=link1 l1.linkClicked=new LinkLabelEventhandler(link1_clicked); l1.Text=Register online Visit microsoft Visit MSN l1.links.Add(0,7,www.rediff.com); l1.links.Add(16,5,www.microsoft.com); L1.links.Add(31,5,www.msn.com); Event handler

Private void link1_Clicked(object sender,EventArgs e)


{ Linklable l2=(LinkLabel) sender //typecast the object to class linklabel l2.LinkVisited = true; l2.VisitedLinkColor = Color.Green System.Diagnostics.Process.Start(e.Link.LinkData.ToString()); }

TextBox
TextBox t1= new TextBoX(); t1.Text=Hello; t1.Name=Input; t1.Multiline=true Appending text: t1.Text+=some text; t1.AppendText(" Appended text");
Accepts return and AcceptsTab In a Multiline TextBox control, you need to press CTRL+ENTER to create a new line. The AcceptsReturn property sets TextBox control to move to new line by simply pressing ENTER key. By default, AcceptsReturn property of a TextBox control is false. t1.AcceptsReturn = true;

TextBox
If a TextBox control is set to multiline, the AcceptsTab property is used to set so the TextBox control accepts TAB key.

If this property is not set, pressing TAB key simply move to the next control on a Form. By
default, AcceptsTab property value of a TextBox control is false.// accepts TAB key t1.AcceptsTab = true; Passoword character casing t1.PasswordChar = '$'; t1.ReadOnly = true ///for output to be displayed in textbox

TextBox properties
WordWrap
If WordWrap property is true, the text in the TextBox control automatically wraps to the next line if required.

If this property is set to true, horizontal scroll bars are not displayed regardless of the
ScrollBars property setting. t1.WordWrap = true;

ScrollBars A Multiline TextBox control can have scrollbars. The ScrollBars property of TextBox control is used to show scrollbars on a control. The ScrollBars property is represented by a ScrollBars enumeration that has four values - Both, Vertical, Horizontal, and None. control and they will be visible when the scrolling is needed on a TextBox control. dynamicTextBox.ScrollBars = ScrollBars.Both;

Read TextBox Contents


string textBoxContents = t1.Text; ///single line textbox string [] textBoxLines = t1.Lines; //multilinetextbox For each (string line in textBoxLines) { MessageBox.Show(line); }

Textchanged event
t1.textchanged=new EventHandler(t1_TextChanged); Event handler Private void t1_TextChanged(object s,EventArgs e) { TextBox t2=(TextBox)s this.text=t2.Text; }

Key event
Private void t1_keyDown(object s,EventArgs e) { If(e.code==Keys.Enter) { Message.Box(You pressed enter); } }

TextBox Events
Event Description Enter Leave Validating Validated KeyDown KeyPress KeyUp

Focus events CausesValidation property set to true

RadioButtons
Radio buttons traditionally display themselves as a label with a tiny circle to the left of it, which can be either selected or not.

To group radio buttons together so they create one logical unit you must
use a GroupBox control or some other container. When you first place a GroupBox onto a form and then place the RadioButton controls you need within the borders of the GroupBox , the RadioButton controls will automatically change their state to reflect that

only one option within the group box can be selected

Property Description
Appearance A radio button can be displayed either as a label with a circular check When it is displayed as a button, the control appears depressed when selected, and not depressed otherwise. AutoCheck When true , a black point is displayed when the user clicks the radio button. When false , the radio button must be manually checked in code from the Click event handler. CheckAlign -This is used to change the alignment of the check box portion of the radio button.

The default is ContentAlignment.MiddleLeft .


Checked Indicates the status of the control. It is true if the control is displaying a black point, and false otherwise.

RadioButton rBut1 = new RadioButton(); rBut1.Text = Red"; rBut1.Checked = true; rBut1.CheckedChanged += new EventHandler(rBut_CheckedChanged); Controls.Add(rBut1);

Checked Changed event


private void rBut_CheckedChanged(object sender, EventArgs e) { RadioButton r1 = sender as RadioButton; ///typecast into radiobutton class if (r1.Checked) { r1.Text=Blue Or Messagebox.show(you have selected the option+r1.Text)

}
else { r1.Text = "UnChecked"; } } }

RadioButton Events
CheckedChanged Click

Example
using System; using System.Windows.Forms; public class Exercise : Form { //Global declaration of controls RadioButton radSmall; RadioButton radMedium;

RadioButton radLarge;
public Exercise()

GroupBox grpPizzaSize;
//constructor that calls Intialise Component method

{ InitializeComponent(); }

private void InitializeComponent() { grpPizzaSize = new GroupBox(); radSmall = new RadioButton(); radMedium = new RadioButton();

radLarge = new RadioButton ()


grpPizzaSize.Controls.Add(radSmall); grpPizzaSize.Controls.Add(radMedium); grpPizzaSize.Controls.Add(radLarge); Controls.Add(grpPizzaSize); }

The Caption of a Radio Button radSmall.Text = "Small"; radMedium.Text = "Medium"; radLarge.Text = "Large"; Event handler string ChosenMovie = ""; if (radSmall.Checked) { ChosenMovie = radSmall.Text; } else if (radLarge.Checked) { ChosenMovie = radLarge.Text; }

CheckBox Properties
Property Description CheckState -Unlike the radio button, a check box can have three states: Checked , Indeterminate , and Unchecked . When the state of the check box is Indeterminate , the control check next to the label is usually grayed, indicating that either the current value of the check is not valid; for some reason cannot be determined (e.g., the check indicates the read - only state of files, and two are

selected, of which one is read - only and the other is not); or has no meaning under the current
circumstances. ThreeState- When false , the user will not be able to change the CheckState state to Indeterminate .

How Do I Determine the State of A CheckBox


private void cbTwo_CheckedChanged(object sender, EventArgs e) { if (cbTwo.CheckState == CheckState.Checked) { MessageBox.Show("Checked"); } else { MessageBox.Show("Unchecked"); } }

CheckBox Events
Event

Description Occurs whenever the Checked property of the check box changes. Occurs whenever the CheckedState property changes. As Checked and Unchecked are both possible values of the CheckedState property, this event is sent whenever the Checked property changes. In addition, it is also sent when the state changes from Checked to Indeterminate.

CheckedChanged CheckStateChanged

AutoCheck Property
Gets or set a value indicating whether the Checked or CheckState values and
the CheckBox's appearance are automatically changed when the CheckBox is clicked.

The RichTextBox Control


The RichTextBox control (System.Windows.Forms.RichTextBox) is similar to a TextBox control but it allows you to format different parts of the text inside it. The TextBox control is typcially used to accept text input from the user while the RichTextBox control is used to show formatted text and save it in Rich Text Format (RTF).

The RichTextBox control allows you to

format parts of the whole text of the


control.

ListBox Control.
enabled you to display a list of items from which the user can select one or multiple items from the list. The default is for the ListBox to list the items vertically however setting the multicolumn property to true the items are listed horizontally

Creating a List Box


Using System.Windows.Forms; public class Exercise : Form { ListBox lbxFamily; public Exercise() //reference to listbox

{ InitializeComponent(); }
private void InitializeComponent() { lbxFamily = new ListBox(); Controls.Add(lbxFamily); } } //create listbox object

Adding Items to a List Box


lbxFamily.Items.Add("Son"); lbxFamily.Items.Add("Daughter"); lbxFamily.Items.Add("Father"); lbxFamily.Items.Add("Mother"); (or)

string[] strMembers = { "Niece", "Nephew", "Uncle" };


lbxFamily.Items.AddRange(strMembers);

Selecting an Item in a List Box


lbxFamily.SelectedIndex = 3;

Selecting and Searching for Items in a ListBox


The SelectionMode property determines the number of items a ListBox allows to be selected at one time. It takes four values from the SelectionMode enumeration: None, Single, Multi- Single, and MultiExtended.
When theSelectionMode property is set to SelectionMode.MultiExtended-

pressing SHIFT and clicking the mouse or pressing SHIFT and one of the arrow keys extends the selection from the previously selected item to the current item. Pressing CTRL and clicking the mouse selects or deselects an item in the list. MultiExtended permits the use of the Shift and Ctrl keys.

listBox1.Sorted = true; listBox1.SelectionMode = SelectionMode.MultiExtended; / Select three initial items from the list. listBox1.SetSelected(0,true); listBox1.SetSelected(2,true); listBox1.SetSelected(4,true);

Exercise

for (int i = loopStart; i <= loopEnd; i++) { listBox1.Items.Clear( );

answer = answer + i; listBox1.Items.Add( answer.ToString() ); }

Responding to the ListBox SelectedIndexChanged event


Assigning a listBox1_SelectedIndexChanged event to the button control.

listBox1.SelectedIndexChanged+=new
EventHandler(listBox1_SelectedIndexChanged);

private void listBox1_SelectedIndexChanged (object sender, EventArgs e) {

MessageBox.Show (listBox1.SelectedItem.ToString());
}

if (listBox1.SelectedIndex = = 1) { loadListBox(); }

Getting All Items


To get all items, we use the Items property and loop through it to read all the items. private void GetItemsButton_Click(object sender, EventArgs e) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); for each (object item in listBox1.Items) { sb.Append(item.ToString()); sb.Append(" "); } MessageBox.Show(sb.ToString());

We can clear all selected items by calling ClearSelected method. listBox1.ClearSelected(); The FindString method is used to find a string or substring in a ListBox int index = listBox1.FindString(textBox1.Text)

The CheckedListBox Control


The CheckedListBox control is similar to the ListBox control except that each item is represented by a CheckBox control. You can select each item like an ordinary ListBox, but in addition, you can also check the box beside each item.

Properties
CheckedIndices-A collection of checked indices of the CheckedListBox control. CheckedItems-A collection of checked items. CheckOnClick-Specifies whether to check the box of an item if the item is selected. ThreeDCheckBoxes-Specifies whether the checkbox should be flat(twodimensional appearance) or normal(three-dimensional appearance).

SelectedIndexChanged event handler


using System.Windows.Forms; namespace WindowsFormsApplication25 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e) { // Get selected index, and then make sure it is valid. int selected = checkedListBox1.SelectedIndex; if (selected != -1) { this.Text = checkedListBox1.Items[selected].ToString(); } } } }

private void WhatIsChecked_Click(object sender, System.EventArgs e) { // Display in a message box all the items that are checked. // First show the index and check state of all selected items. for each(int indexChecked in checkedListBox1.CheckedIndices)

{ // The indexChecked variable contains the index of the item.


MessageBox.Show("Index#: " + indexChecked.ToString() + ", is checked. Checked state is:" + checkedListBox1.GetItemCheckState(indexChecked).ToString() + "."); }

// Next show the object title and check state for each item selected. For each(object i in checkedListBox1.CheckedItems) { // Use the IndexOf method to get the index of an item.

MessageBox.Show("Item with title: \"" + i.ToString() + "\", is checked.


Checked state is: " + checkedListBox1.GetItemCheckState(checkedListBox1.Items.IndexOf(i)).T oString() + "."); } }

MENUS
A menu on a form is created with a MainMenu object, which is a collection of MenuItem objects. Can add menus to Windows Forms at design time by adding the MainMenu control and then adding menu items to it using the Menu Designer. Menus can also be added programmatically by adding one or more MainMenu controls to a form and adding MenuItem objects to the collection.

VISUAL STUDIO 2010-MENU CREATION

VISUAL STUDIO 2010-MENU CREATION

A submenu which contains another submenu can be identified by the arrow at its right side.

MENU CREATION
Each text menu item you add is represented by ToolStripMenuItem. The separator is represented by ToolStripSeparator. The ToolStripSeparator is only used to separate related menus. Each ToolStrip MenuItem is added to the MenuStrips Item property

Each submenu is added to the ToolStrip MenuItems DropDown Items property.

Visual Studio automatically adds a name to each


ToolStripMenuItem control which is based on the text you specified.

To add a MenuStrip writing code


Create the MenuStrip control and add it to the forms. MenuStrip MainMenu = new MenuStrip();

this.Controls.Add(MainMenu);
//Add the File menu Item and add it to the MenuStrip above. ToolStripMenuItem obj1 = new ToolStripMenuItem("File"); MainMenu.Items.Add(obj1); //Item property of menu strip

//Create the New menu Items and add it to the File Menu above. We are also going to create the click event for the item. ToolStripMenuItem New = new ToolStripMenuItem("New"); New.Click += new EventHandler(New_Click); obj1.DropDownItems.Add(New);

Property
Checked
Tells whether the item is checked. CheckOnClick Tells whether an item will be checked or unchecked when it is clicked. CheckState- Tells whether the item is checked or unchecked.

DropDownItems-A collection of submenus of the current item.


Enabled-Enables or disables this item. Image-An optional image or icon that is shown at the left of the label.

Property
ShortcutKeys-The shortcut keys associated with the ToolStripMenuItem. ShowShortcutKeys-Tells whether the shortcut keys for an item is shown in the menu. Text-The text or label of the menu item. ToolTipText-The text inside the tool tip that appears when you hover your mouse on the menu item.

Adding Shortcut Keys to a Menu Item


Can add shortcut keys to a menu item. The easiest one is by using the & (ampersand) character when typing the name of the menu item.
The letter following the & character will be
considered as the shorcut key. For example, &Save will have S as the shortcut

key and E&xit will have the X as the shortcut


key.

ShortcutKeys property. Select a menu item and then go to the Properties Window and find the ShortcutKeys property.

MainMenu.Dock = DockStyle.Left; FileMenu.BackColor = Color.OrangeRed; FileMenu.ForeColor = Color.Black;

FileMenu.Text = "File Menu";


FileMenu.Font = new Font("Georgia", 16); FileMenu.ToolTipText = "Click Me";

Menu Item Click Event Handler


private void FileMenuItemClick(object sender, EventArgs e) { MessageBox.Show("File menu item clicked"); }