You are on page 1of 80

Visual Programming

Session: 3 Selva kumar S

Quick Recap
Using Development Environment Features Creating a Windows Application Creating a Web Application Creating a Console Application Visual basic Statements Data Types Using Variables Why use windows form Windows form class Hierarchy Forms Method/ Event/ Properties Creating MDI forms Creating Inherited forms

Windows Forms: Text Boxes, Rich Text Boxes, Labels, and Link Labels

The Control Class


The Control class is in the System.Windows.Forms namespace. It serves as a base class for the Windows controls such as rich text boxes which have this class hierarchy
Object MarshalByRefObject Component Control TextBoxBase RichTextBox

Text Boxes
box-like controls in which you can enter text. Text boxes can be multiline, have scroll bars, be read-only, and have many other attributes The TextBox class is derived from the TextBoxBase class, which is based on Control:
Object MarshalByRefObject Component Control TextBoxBase TextBox Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click TextBox1.Text = "Hello from Visual Basic" End Sub

Accessing Text in a Text Box


Private Sub Button1_Click_1(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click TextBox1.Text = "Hello from Visual Basic" End Sub
Private Sub Button1_Click_1(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim strText As String strText = TextBox1.Text End Sub

Adding Scroll Bars to Text Boxes


Using the ScrollBars property, there are four ways to add scroll bars to a text box; here are the settings you use for ScrollBars, and the type of scroll bars each setting displays: 0: None 1: Horizontal 2: Vertical 3: Both

Making a Text Box Read-only


Using the ReadOnly Property In VB6 and before, you used the Locked property to "lock" a text box so it couldn't be edited, but now the Locked property is used to lock controls in position. Now you use the ReadOnly property to make a text box read-only. Setting this property to True means that the user cannot enter text into the text box (except under your program's control in code). Disabling a Text Box You also can disable a text box by setting its Enabled property to False. However, although this means the user can't enter text into the text box, it also means the text in the box appears grayed. Disabling is better done to indicate that the control is inaccessible. Using Labels Instead of Text Boxes Another alternative to using read-only text boxes is to display read-only text in label controls. You can change the text in a label control from code using the label's Text property.

Selecting and Replacing Text in a Text Box

To work with part of the text in a text box, you select the text you want using three properties: SelectionLength Returns or sets the number of characters selected. SelectionStart Returns or sets the starting point of text selected; indicates the position of the insertion point if no text is selected. SelectedText Returns or sets the string containing the currently selected text; consists of a zero-length string ("") if no characters are selected.
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click TextBox1.SelectionStart = 0 TextBox1.SelectionLength = Len(TextBox1.Text) TextBox1.SelectedText = "Hello from Visual Basic" End Sub

Copying or Getting Selected Text to or from the Clipboard


Public Class Form1 Inherits System.Windows.Forms.Form 'Windows Form Designer generated code Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click System.Windows.Forms.Clipboard.SetDataObject_ (TextBox1.SelectedText) End Sub Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click Dim ClipboardData As System.Windows.Forms.IDataObject = _ System.Windows.Forms.Clipboard.GetDataObject() If ClipboardData.GetDataPresent(DataFormats.Text) Then TextBox2.Text = ClipboardData.GetData(DataFormats.Text) End If End Sub End Class

Creating a Password Control


To convert a standard text box into a password box, you just assign some character (usually an asterisk, "*") to the text box's PasswordChar property.

Controlling Input in a Text Box


Private Sub TextBox1_KeyPress(ByVal sender As Object, _ ByVal e As System.Windows.Forms.KeyPressEventArgs) _ Handles TextBox1.KeyPress If (e.KeyChar < "0" Or e.KeyChar > "9") Then MsgBox("Please enter single digits") End If End Sub Private Sub TextBox1_KeyPress(ByVal sender As Object, _ ByVal e As System.Windows.Forms.KeyPressEventArgs) _ Handles TextBox1.KeyPress If (e.KeyChar < "0" Or e.KeyChar > "9") Then e.Handled = True End If End Sub Private Sub TextBox1_TextChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles TextBox1.TextChanged TextBox2.Text = sender.Text End Sub

Creating a Text Box in Code


Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim TextBox1 As New TextBox() TextBox1.Size = New Size(150, 20) TextBox1.Location = New Point(80, 20) TextBox1.Text = "Hello from Visual Basic" Me.Controls.Add(TextBox1) End Sub

Rich Text Boxes


The RichTextBox control does everything the TextBox control does, but in addition, it can display fonts, colors, and links; load text and embedded images from a file; undo and redo editing operations; and find specified characters.
Object MarshalByRefObject Component Control TextBoxBase RichTextBox

Accessing Text in a Rich Text Box


Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click RichTextBox2.Text = RichTextBox1.Text End Sub
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click RichTextBox2.Rtf = RichTextBox1.Rtf End Sub

Creating Bold, Italic, Underlined, and Strikeout Text


Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click RichTextBox1.SelectionStart = RichTextBox1.Find("italic") Dim ItalicFont As New Font(RichTextBox1.Font, FontStyle.Italic) RichTextBox1.SelectionFont = ItalicFont RichTextBox1.SelectionStart = RichTextBox1.Find("bold") Dim BoldFont As New Font(RichTextBox1.Font, FontStyle.Bold) RichTextBox1.SelectionFont = BoldFont RichTextBox1.SelectionStart = RichTextBox1.Find("underlined") Dim UnderlineFont As New Font(RichTextBox1.Font, FontStyle.Underline) RichTextBox1.SelectionFont = UnderlineFont RichTextBox1.SelectionStart = RichTextBox1.Find("strikeout") Dim StrikeoutFont As New Font(RichTextBox1.Font, FontStyle.Strikeout) RichTextBox1.SelectionFont = StrikeoutFont End Sub

Adding Bullets to Rich Text Boxes


Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button4.Click RichTextBox1.Text = "This rich text box shows how to use bullets " + _ "and indent bulleted text." RichTextBox1.SelectionIndent = 20 RichTextBox1.BulletIndent = 10 RichTextBox1.SelectionBullet = True End Sub

Saving and Loading RTF Files from and to Rich Text Boxes
Private Sub Button6_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button6.Click RichTextBox3.SaveFile("text.rtf") RichTextBox1.LoadFile("text.rtf") End Sub

Creating Rich Text Boxes in Code


Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim RichTextBox1 As New RichTextBox() RichTextBox1.Size = New Size(150, 100) RichTextBox1.Location = New Point(70, 20) RichTextBox1.Text = "Hello from Visual Basic" Me.Controls.Add(RichTextBox1) End Sub

Labels
Labels usually are used to display text that cannot be edited by the user.
Object MarshalByRefObject Component Control Label

Handling Label Events


labels have events like Click and DoubleClick
Private Sub Label1_DoubleClick(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Label1.DoubleClick Label1.Text = "Quit clicking me!" End Sub

Using Labels to Give Access Keys to Controls without Captions


Add access key to a label control, and then make sure the control you want to give the focus to with that access key is next in the tab order (i.e., has the next highest TabIndex property value). Because labels cannot accept the focus themselves, this is a neat feature; when the user presses Alt and the access key, the label passes the focus on to the next control. In this way, you can give even controls like text boxes access keys. When you use access keys, make sure you set the label's UseMnemonic property to True (the default), or the access key won't be enabled.

Link Labels
Link labels are new in VB .NET. They're based on the Label class, but also let you support Web-style hyperlinks to the Internet and other Windows forms
Object MarshalByRefObject Component Control Label LinkLabel

Creating a LinkLabel
Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, _ ByVal e As ystem.Windows.Forms.LinkLabelLinkClickedEventArgs) _ Handles LinkLabel1.LinkClicked LinkLabel1.LinkVisited = True System.Diagnostics.Process.Start("www.coriolis.com") End Sub

Creating a LinkLabel in Code


Private WithEvents LinkLabel1 As LinkLabel Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click LinkLabel1 = New LinkLabel() LinkLabel1.AutoSize = True LinkLabel1.Location = New Point(15, 15) LinkLabel1.Size = New Size(135, 15) LinkLabel1.Text = _ "Interested in Black Books? Click here to see them all! LinkLabel1.Links.Add(14, 11, "info") LinkLabel1.Links.Add(33, 4, "www.coriolis.com") AddHandler LinkLabel1.LinkClicked, AddressOf e.LinkLabel1_LinkClicked Me.Controls.Add(LinkLabel1) End Sub

Linking to Another Form


Private Sub LinkLabel1_LinkClicked(ByVal sender As Object, _ ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) LinkLabel1.Links(LinkLabel1.Links.IndexOf(e.Link)).Visited = True If (e.Link.LinkData.ToString() = "info") Then Dim InfoWindow As New Form2() InfoWindow.Show() End If End Sub

Linking to the Web


Private Sub LinkLabel1_LinkClicked(ByVal sender As Object, _ ByVal e As ystem.Windows.Forms.LinkLabelLinkClickedEventArgs) LinkLabel1.Links(LinkLabel1.Links.IndexOf(e.Link)).Visited = True If (e.Link.LinkData.ToString() = "info") Then Dim InfoWindow As New Form2() InfoWindow.Show() Else System.Diagnostics.Process.Start(e.Link.LinkData.ToString()) End If End Sub

Buttons

There is no more popular control in Visual Basic than buttons, with the possible exception of text boxes. Buttons are the plain controls that you simply click and release. Besides using buttons in forms directly, they're very popular in dialog boxes. you can set the AcceptButton or CancelButton property of a form to let users click a button by pressing the Enter or Esc keys-even if the button does not have focus. And when you display a form using the ShowDialog method, you can use the DialogResult property of a button to specify the return value of ShowDialog. You also can change the button's appearance, giving it an image or aligning text and images in it as you like. You can even-make it look flat for a "Web" look, setting the FlatStyle property to FlatStyle.Flat. Or, you can set the FlatStyle property to FlatStyle.Popup, which means it looks flat until the mouse pointer passes over it, when the button pops up to give it the standard Windows button appearance.

Setting a Button's Caption


Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Button1.Text = "You clicked me!" End Sub

Setting a Button's Foreground and Background Color


Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Button1.BackColor = Color.Blue End Sub

Setting Button Fonts


Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Button1.Font = New Font(Button1.Font, FontStyle.Italic) End Sub

Imitating Control Arrays


You've decided that your new game program really does need 144 buttons in the main form, arranged in a grid of 12 12. But what a pain it is to write 144 subroutines to handle the click event for each of them! Control arrays don't exist in Visual Basic .NETat least, they're not built in anymore. However, you can still create something very like a control array yourself, in code. The main feature of control arrays is that all the controls in it share the same event handler, and you can use the AddHandler method to assign the same event handler to multiple controls.

Public Class Form1 Inherits System.Windows.Forms.Form Private Sub Button_Click(ByVal sender As System.Object, _ Dim WithEvents Button1 As Button ByVal e As System.EventArgs) Dim WithEvents Button2 As Button If sender Is Button1 Then Dim WithEvents Button3 As Button TextBox1.Text = "You clicked button 1" Friend WithEvents Button4 As Button End If Friend WithEvents TextBox1 As TextBox If sender Is Button2 Then 'Windows Form Designer generated code TextBox1.Text = "You clicked button 2" Private Sub Button4_Click(ByVal sender As System.Object, _ End If ByVal e As System.EventArgs) Handles End Sub Button4.Click Button1 = New Button() End Class Button2 = New Button() Button3 = New Button() Button1.Size = New Size(80, 30) Button1.Location = New Point(115, 20) Button1.Text = "Button 1" Button2.Size = New Size(80, 30) Button2.Location = New Point(115, 60) Button2.Text = "Button 2" Button3.Size = New Size(80, 30) Button3.Location = New Point(115, 100) Button3.Text = "Button 3" Controls.Add(Button1) Controls.Add(Button2) Controls.Add(Button3) AddHandler Button1.Click, AddressOf Button_Click AddHandler Button2.Click, AddressOf Button_Click AddHandler Button3.Click, AddressOf Button_Click

Setting Button Tab Order


To make your buttons more accessible from the keyboardespecially if you've got a lot of themyou can use the TabStop and TabIndex properties. Here's what those properties do: TabStop indicates if this button can accept the focus when the user tabs to it. TabIndex is the index of the current button in the tab order (starts at 0). When the user presses the Tab key, the focus moves from button to button, ascending through the tab order.

Disabling Buttons
you can-you can disable the button by setting its Enabled property to False when it's inappropriate to use that button
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Button1.Enabled = False End Sub

Showing and Hiding Buttons


To make a button disappear, just set its Visible property to False. To make it reappear, set the Visible property to True.
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Button1.Visible = False End Sub

Resizing and Moving Buttons from Code


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Button1.Size = New Size(100, 50) Button1.Location = New Point(0, 0) End Sub

Adding a Picture to a Button


Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Button1.Image = _ Image.FromFile("C:\vbnet\ch06\imagebuttons\clicked.jpg") Button1.ImageAlign = ContentAlignment.TopLeft Button1.Text = "" Button1.FlatStyle = FlatStyle.Flat TextBox1.Text = "You clicked the button" End Sub

Passing Buttons to Procedures


Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click SetCaption(Button1) End Sub
Private Sub SetCaption(ByRef TargetButton As Button) TargetButton.Text = "I've been clicked End Sub

Checkboxes
Checkboxes are also familiar controlsyou click a checkbox to select it, and click it again to deselect it. When you select a checkbox, a check appears in it, indicating that the box is indeed selected. You use a checkbox to give the user an option, such as true/false or yes/no. The checkbox control can display an image or text or both.

Getting a Checkbox's State: Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click If CheckBox1.Checked Then Button1.Text = "The check mark is checked" End If End Sub Setting a Checkbox's State: Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click CheckBox1.Checked = True End Sub

Creating Three-State Checkboxes

You use the CheckState property to get or set the value of the three-state checkbox. The three states are: Checked A check appears in the checkbox. Unchecked No check appears in the checkbox. Indeterminate A check appears in the checkbox on a gray background.

Radio Buttons
Radio buttons, also called option buttons, are similar to checkboxesthe user can select and deselect themexcept for two things: they are round where checkboxes are square, and you usually use radio buttons together in groups.

Getting a Radio Button's State


Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click If RadioButton1.Checked Then MsgBox ("The Radio Button is selected.") Else MsgBox ("The Radio Button is not selected.") End If End Sub

Setting a Radio Button's State


Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click RadioButton1.Checked = True End Sub

Panels
You use panels to group other controls, usually to divide a form into regions by function. For example, you may have a menu form that lets the user select drinks in one panel and what they want on their sandwich in another. You can use grouping controls such as panels and group controls to make it clear which controls are associatedand it makes it easier to handle groups of controls at design time too, because when you move a panel, all the controls it contains are moved as well.

Adding Controls to Panels in Code


Public Class Form1 Inherits System.Windows.Forms.Form 'Windows Form Designer generated code Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim Panel1 As New Panel() Dim TextBox1 As New TextBox() Dim Label1 As New Label() Panel1.Location = New Point(60, 20) Panel1.Size = New Size(100, 150) Panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D Label1.Location = New Point(16, 16) Label1.Text = "Enter text:" Label1.Size = New Size(60, 16) TextBox1.Location = New Point(16, 32) TextBox1.Text = "" TextBox1.Size = New Size(60, 20) Me.Controls.Add(Panel1) Panel1.Controls.Add(Label1) Panel1.Controls.Add(TextBox1) End Sub End Class

Group Boxes
Like panels, group boxes are used to provide a grouping for other controls. Group boxes are similar to panels, but, as mentioned above, only group boxes display captions and only the panels can have scroll bars. Group boxes display frames around their contained controls and can display text in a caption

Adding Controls to Group Boxes in Code


Public Class Form1 Inherits System.Windows.Forms.Form Dim GroupBox1 As New GroupBox() Dim WithEvents RadioButton1 As RadioButton Dim WithEvents RadioButton2 As RadioButton Dim WithEvents RadioButton3 As RadioButton 'Windows Form Designer generated code Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click RadioButton1 = New RadioButton() RadioButton2 = New RadioButton() RadioButton3 = New RadioButton() GroupBox1.Text = "GroupBox1" GroupBox1.Location = New Point(40, 40) GroupBox1.Size = New Size(200, 100) RadioButton1.Location = New Point(16, 16) RadioButton1.Text = "RadioButton1" RadioButton1.Size = New Size(120, 16) RadioButton2.Location = New Point(16, 32) RadioButton2.Text = "RadioButton2 RadioButton2.Size = New Size(120, 20) GroupBox1.Controls.Add(RadioButton1) GroupBox1.Controls.Add(RadioButton2) GroupBox1.Controls.Add(RadioButton3) Controls.Add(GroupBox1) AddHandler RadioButton1.CheckedChanged, AddressOf _ RadioButton1_CheckedChanged ..

List Boxes
list boxes display a list of items from which the user can select one or more. If there are too many items to display at once, a scroll bar automatically appears to let the user scroll through the list. In Visual Basic .NET, each item in a list box is itself an object.

Adding Items to a List Box


You can add items to a list box at either design time or at run time; the first item will have index 0, the next index 1, and so on in the list box. At design time, you can use the Items property, which is a very handy array of the items in the list box, and at run time, you can use both the Items property and the Add (formerly AddItem) method.

Referring to Items in a List Box by Index


Private Sub ListBox1_SelectedIndexChanged(ByVal sender As _ System.Object, ByVal e As System.EventArgs) Handles _ ListBox1.SelectedIndexChanged TextBox1.Text = "You selected item " & ListBox1.SelectedIndex + 1 End Sub

Responding to List Box Events


Private Sub ListBox1_SelectedIndexChanged(ByVal sender As _ System.Object, ByVal e As System.EventArgs) Handles _ ListBox1.SelectedIndexChanged TextBox1.Text = "You selected item " & ListBox1.SelectedIndex + 1 End Sub

Removing Items from a List Box


You can use the RemoveAt method to delete items from a list box. To remove the item at index 5, you'd use this code: ListBox1.Items.RemoveAt(5) Here's how you'd remove the currently selected item with RemoveAt: ListBox1.Items.RemoveAt(ListBox1.SelectedIndex) You also can use the Remove method to remove a specific object from a list box. Here's how I'd remove the currently selected item with Remove: ListBox1.Items.Remove(ListBox1.SelectedItem) You also can remove items by passing the corresponding object to Remove. For example, if I've filled a list box with String objects, I can remove the item "Item 1" this way: ListBox1.Items.Remove ("Item 1")

Determining How Many Items Are in a List Box

Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim intLoopIndex As Integer For intLoopIndex = 0 To ListBox1.Items.Count - 1 MsgBox(ListBox1.Items(intLoopIndex)) Next End Sub

Determining Which List Box Items Are Selected

Private Sub ListBox1_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles ListBox1.Click TextBox1.Text = ListBox1.SelectedItem.ToString() End Sub
For Each Item In ListBox1.SelectedItems TextBox1.Text &= Item.ToString() Next

Making List Boxes Scroll Horizontally


Dim ListBox1 As ListBox Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click ListBox1 = New ListBox() ListBox1.Size = New System.Drawing.Size(270, 100) ListBox1.Location = New System.Drawing.Point(10, 40) Me.Controls.Add(ListBox1) ListBox1.MultiColumn = True
ListBox1.BeginUpdate() Dim intLoopIndex As Integer For intLoopIndex = 1 To 20 ListBox1.Items.Add("Item " & intLoopIndex.ToString()) Next intLoopIndex ListBox1.EndUpdate() End Sub

Creating Multiselect List Boxes


Dim ListBox1 As ListBox Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click ListBox1 = New ListBox() ListBox1.Size = New System.Drawing.Size(270, 100) ListBox1.Location = New System.Drawing.Point(10, 40) AddHandler ListBox1.SelectedIndexChanged, AddressOf _ ListBox1_SelectedIndexChanged Me.Controls.Add(ListBox1) ListBox1.MultiColumn = True ListBox1.SelectionMode = SelectionMode.MultiExtended ListBox1.BeginUpdate() Dim intLoopIndex As Integer For intLoopIndex = 1 To 20 ListBox1.Items.Add("Item " & intLoopIndex.ToString()) Next intLoopIndex ListBox1.EndUpdate() ListBox1.SetSelected(1, True) ListBox1.SetSelected(3, True) ListBox1.SetSelected(5, True) End Sub

Clearing a List Box


Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click ListBox1.Clear() End Sub

Checked List Boxes


Windows forms checked list boxes are derived from standard list boxes, except that they also support a checkbox for each item

Adding Items to Checked List Boxes


Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click CheckedListBox1.BeginUpdate() Dim intLoopIndex As Integer For intLoopIndex = 1 To 20 CheckedListBox1.Items.Add("Item " & intLoopIndex.ToString(), True) Next intLoopIndex CheckedListBox1.EndUpdate() End Sub

Determining What Items Are Checked in Checked List Boxes


Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click Dim intLoopIndex As Integer Dim strText, strData As String strText = "Checked Items: " For intLoopIndex = 0 To (CheckedListBox1.Items.Count - 1) If CheckedListBox1.GetItemChecked(intLoopIndex) = True Then strText &= CheckedListBox1.Items(intLoopIndex).ToString & ", " End If Next TextBox1.Text = strText End Sub

Checking or Unchecking Items in Checked List Boxes from Code


Private Sub Button3_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button3.Click CheckedListBox1.SetItemChecked(0, False) End Sub

Handling Item Check Events in Checked List Boxes


Private Sub CheckedListBox1_ItemCheck(ByVal sender As Object, _ ByVal e As System.Windows.Forms.ItemCheckEventArgs) Handles _ CheckedListBox1.ItemCheck Select Case e.NewValue Case CheckState.Checked TextBox1.Text = "Item " & e.Index + 1 & " is checked" Case CheckState.Unchecked TextBox1.Text = "Item " & e.Index + 1 & " is not checked End Select End Sub

Combo Boxes
The Windows forms combo box control is used to display data in a drop-down combo box. The combo box is made up of two parts: The top part is a text box that allows the user to type in all or part of a list item. The other part is a list box that displays a list of items from which the user can select one or more.

Adding Items to a Combo Box


Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click ComboBox1.BeginUpdate() Dim intLoopIndex As Integer For intLoopIndex = 0 To 20 ComboBox1.Items.Add("Item " + intLoopIndex.ToString()) Next ComboBox1.Text = "Select one..." ComboBox1.EndUpdate() End Sub

Responding to Combo Box Selections


TextChanged Events
Private Sub ComboBox1_TextChanged(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles ComboBox1.TextChanged TextBox1.Text = ComboBox1.Text End Sub

SelectedIndexChanged Events
Private Sub ComboBox1_SelectedIndexChanged(ByVal _ sender As System.Object, ByVal e As System.EventArgs) _ Handles ComboBox1.SelectedIndexChanged Dim SelectedIndex As Integer SelectedIndex = ComboBox1.SelectedIndex Dim SelectedItem As Object SelectedItem = ComboBox1.SelectedItem TextBox1.Text = "Selected item text: " & SelectedItem.ToString() & _ " Selected index: " & SelectedIndex.ToString() End Sub

Removing Items from a Combo Box


Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) ComboBox1.Items.RemoveAt(1) End Sub

Getting the Current Selection in a Combo Box


Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click Dim selectedIndex As Integer selectedIndex = ComboBox1.SelectedIndex Dim selectedItem As Object selectedItem = ComboBox1.SelectedItem TextBox1.Text = "Selected item text: " & selectedItem.ToString() & _ " Selected index: " & selectedIndex.ToString() End Sub

Sorting a Combo Box


For example, say we set the Sorted property to True for a combo box, ComboBox1. Now it doesn't matter in what order you add items to that combo box:
Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ComboBox1.Items.Add("zebra") ComboBox1.Items.Add("tiger") ComboBox1.Items.Add("hamster") ComboBox1.Items.Add("aardvark") End Sub

Picture Boxes
Picture boxes are used to display graphics from a bitmap, icon, JPEG, GIF or other image file type.
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click PictureBox1.Image = _ Image.FromFile("c:\vbnet\ch07\pictureboxes\image.jpg") End Sub

Adjusting Picture Box Size to Contents


Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage PictureBox1.ClientSize = New Size(300, 100) End Sub

Handling Picture Box Events (and Creating Image Maps)


Private Sub PictureBox1_MouseDown(ByVal sender As Object, _ ByVal e As System.Windows.Forms.MouseEventArgs) Handles _ PictureBox1.MouseDown TextBox1.Text = "You clicked at " & e.X & ", " & e.Y End Sub

Scroll Bars
vertical or horizontal controls that display a scroll box or thumb that you can manipulate, and when you drag it to a new position, the value of the scroll bar changes, causing a corresponding action in the program.

Setting Scroll Bars' Minimum and Maximum Values Setting Up Scroll Bar Clicks (Large Changes) Setting Up Scroll Bar Arrow Clicks (Small Changes) Getting and Setting a Scroll Bar's Current Value
Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load HScrollBar1.Minimum = 0 HScrollBar1.Maximum = 100 HScrollBar1.LargeChange = 10 HScrollBar1.SmallChange = 1 HScrollBar1.Value = 20 End Sub

Handling Scroll Bar Events


Private Sub HScrollBar1_Scroll(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.ScrollEventArgs) Handles _ HScrollBar1.Scroll Label1.Location = New Point(e.NewValue * Me.Size.Width / 100, _ Label1.Location.Y) Label1.Text = "I'm moving!" End Sub Private Sub VScrollBar1_Scroll(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.ScrollEventArgs) Handles _ VScrollBar1.Scroll Label1.Location = New Point(Label1.Location.X, _ e.NewValue * Me.Size.Height / 100) Label1.Text = "I'm moving!" End Sub Private Sub HScrollBar2_Scroll(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.ScrollEventArgs) Handles _ HScrollBar2.Scroll TextBox1.Text = "Scroll position: " & e.NewValue End Sub

Coordinating Scroll Bar Pairs


Private Sub VScrollBar1_Scroll(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.ScrollEventArgs) Handles _ VScrollBar1.Scroll VScrollBar2.Value = e.NewValue End Sub
Private Sub VScrollBar2_Scroll(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.ScrollEventArgs) Handles _ VScrollBar2.Scroll VScrollBar1.Value = e.NewValue End Sub

Splitters

splitter controls let you resize controls, extending them as needed, or tucking them away when their job is over. You can use splitters to let the user resize controls. Here's how it works: you add a control to a form, then dock it. Next, you add a splitter and dock it to the same side of the same container, which places the control just before the splitter in the docking order. When you run the program, the splitter is invisible until the mouse passes over it, when the splitter changes the mouse cursor, indicating that the control can be resized,

Track Bars
Track bars are very much like scroll bars but differ in appearance. Track bars look more like controls you might see on stereos
Private Sub TrackBar1_Scroll(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles TrackBar1.Scroll TextBox1.Text = "Track bar value: " & TrackBar1.Value End Sub

Pickers
There are two types of pickersdate-time pickers, and month calendar controls.
Private Sub DateTimePicker1_ValueChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles DateTimePicker1.ValueChanged TextBox1.Text = "Date selected: " & DateTimePicker1.Text End Sub Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load DateTimePicker1.Format = DateTimePickerFormat.Custom DateTimePicker1.CustomFormat = "MMMM dd hh:mm:ss tt" End Sub Private Sub MonthCalendar1_DateSelected(ByVal sender As Object, _ ByVal e As System.Windows.Forms.DateRangeEventArgs) Handles _ MonthCalendar1.DateSelected TextBox1.Text = "Day of the month selected: " & _ MonthCalendar1.SelectionRange.Start.Day End Sub

Notify Icons
This is a pretty cool one, new to Visual Basic .NET. Notify icons let you display an icon in the status notification area of the Windows taskbar (in the indented panel at extreme right in the taskbar) called the Windows system tray.

Tool Tips
small windows that appear with explanatory text when you let the mouse rest on a control or window. That's what tool tips are used for to give quick help when the mouse rests on an item.
ToolTip1.SetToolTip(Button1, "This is a button") Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ToolTip1.SetToolTip(Me, "This is a form.") ToolTip2.SetToolTip(Button1, "This is a button") End Sub

Timers
Timers are also very useful controls, because they let you create periodic events. Strictly speaking, timers are no longer controls but components, and they do not appear in a window at run time.

Handling Timer Eventsand Creating an Alarm Clock


Public Class Form1 Inherits System.Windows.Forms.Form Windows Form Designer generated code Dim blnAlarm As Boolean = False Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick Label1.Text = TimeOfDay If TextBox1.Text <> "" And TextBox2.Text <> "" And TextBox3.Text <> "" Then Dim AlarmTime = New DateTime(Tod ay.Year, Today.Month, _ Today.Day, CInt(TextBox1.Text), CInt(TextBox2.Text), CInt(TextBox3.Text)) If Now > AlarmTime And blnAlarm Then Beep() End If End If End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Timer1.Enabled = True End Sub Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles RadioButton1.CheckedChanged If RadioButton1.Checked Then blnAlarm = True End If End Sub Private Sub RadioButton2_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles RadioButton2.CheckedChanged If RadioButton1.Checked Then blnAlarm = False End If End Sub End Class

Summary
Windows Forms: Text Boxes, Rich Text Boxes, Labels, and Link Labels Button Check box, radio box, panels Picture Boxes Scroll Bars Splitters Track Bars Notify Icons Tool Tips Timers

You might also like