Thursday, March 16, 2023

VB .Net Programming Unit-III:

   

VB .Net Programming 

Unit-III: 

Working with Forms: 

Loading, showing and hiding forms, controlling One form within another.  GUI Programming with Windows Form: 

Textbox Properties, Methods and Events,  

Label Properties, Methods and Events, 

Button, Listbox Properties, Methods and Events,  

Combobox Properties, Methods and Events,  

Checkbox Properties, Methods and Events,  

PictureBox Properties, Methods and Events,  

Radio Button Properties, Methods and Events, 

Panel, Scroll bar, Timer, List View, Tree View, Toolbar, Status Bar OpenFileDialog,  

SaveFileDialog,  

FontDialog,  

ColorDialog,  

Print Dialog. 

LinkLabel. 

Designing menus: 

Context Menu, access & shortcut keys.


  

Working with Forms: 

A Form is used in VB.NET to create a form-based or window-based application. Using the form, we  can build a attractive user interface. It is like a container for holding different control that allows the  user to interact with an application. The controls are an object in a form such as buttons, Textboxes, Textarea, labels, etc. 

A Form uses a System.Windows.Form namespace, and it has a wide family of controls that  add both forms and functions in a Window-based user interface. 

For creating a Windows Forms application 

GoTo File Menu.  

Click on New Project. 

Click on Windows Forms App or Application 

LOADING FORM. 

Public Class Form1 

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load  Dim button1 As New Button() 

Dim button2 As New Button() 

button1.Text = "OK" 

button1.Location = New Point(10, 10)  

button2.Text = "Cancel"  

button2.Location = _ 

New Point(button1.Left, button1.Height + button1.Top + 10)  

Me.Text = "Wel-Come To VB .Net" 

Me.HelpButton = True 

Me.FormBorderStyle = FormBorderStyle.FixedDialog  

Me.MaximizeBox = False 

Me.MinimizeBox = False 

Me.AcceptButton = button1  

Me.CancelButton = button2 

Me.StartPosition = FormStartPosition.CenterScreen  

Me.Height = 300 

Me.Width = 560  

Me.Controls.Add(button1)  

Me.Controls.Add(button2

End Sub  

End Class 

Showing and Hiding Forms 

Visual Basic.NET, everything is an object, and objects are based on classes. Because the definition of a  form is a class, you have to create a new Form object using the class as a template.


  

The process of creating an object from a class (or template) is called instantiation. The syntax you'll use  most often to instantiate a form is the following: 

Dim {objectvariable} As New {formclassname()} 

The three parts of this declaration are 

The Dim statement A reserved word that tells the compiler that you're creating a variable. The name of the variable This will be the name for the form that you will use in code. The keyword New Indicates that you want to instantiate a new object for the variable. 

frmLoginDialog.Show 

or 

frmLoginDialog.Visible = True

HIDING FORM. 

First, you can make a form disappear without closing it or freeing its resources (this is called hiding). 

Set its visible property to False. This hides the visual part of the form, but the form still resides in memory  and can still be manipulated by code. 

All the variables and controls of the form retain their values when a form is hidden, so that if the form is  displayed again, the form looks the same as it did when its visible property was set to False. 

Second, you can completely close a form and release the resources it consumes. You should close a form  when it's no longer needed, so Windows can reclaim all resources used by the form. To do so, you invoke  the Close method of the form like this: 

Me.Close() 

Because Me represents the current Form object, you can manipulate properties and call methods of the  current form using Me. (Me.Visible = False). 

The Close method tells Visual Basic to not simply hide the form, but to destroy it completely. If variables in  other forms are holding a reference to the form you close, their references will be set to nothing and will no  longer point to a valid Form object. 


  

Controlling One Form from within Another 

Controlling the form means accessing its controls, and setting or reading values from within another  form’s code. 

When you are dealing with Windows Forms it's quite likely that sooner or later you are going to want  to pass the data held in a control on one form over to another form. 

the text a user has entered in a text box, a selection from a combobox, a checkbox's Checked  property, etc. You may also want to insert data into a control on another form. 

Public Class Form

Inherits System.Windows.Forms.For

Private Sub UserLabel_Click(ByVal sender As System.Object, ByVal e ASystem.EventArgs) Handles UserLabel.Click 

End Sub 

Private Sub ShowButton_Click(ByVal sender As System.Object, ByVal e ASystem.EventArgs) Handles ShowButton.Click 

Dim F2 As New Form2()  

Me.UserLabel.Text = " "  

F2.ShowDialog(Me

Me.UserLabel.Text = "Current User : " & Form2.NuNameTB.Text  

End Sub 

End Class


  

Public Class Form

Public Shared NuNameTB As TextBo

Private Sub CloseButton_Click(ByVal sender As System.Object, ByVal e ASystem.EventArgs) Handles CloseButton.Click 

NuNameTB = UsersName  

' Now close the form  

Me.Close() 

End Sub  

End Class 

GUI Programming with Windows Form: 

Textbox Properties, Methods and Events 

A TextBox control is used to display, accept the text from the user as an input, or a single line of text  on a VB.NET Windows form at runtime. Furthermore, we can add multiple text and scroll bars in  textbox control. However, we can set the text on the textbox that displays on the form. 

Properties 

AutoCompleteMode- Gets or sets an option that controls how automatic completion works for the  TextBox. 

Font - Gets or sets the font of the text displayed by the control. 

Lines- Gets or sets the lines of text in a text box control. 

TextAlign 

Gets or sets how text is aligned in a TextBox control. This property has values − 

Left, Right, Center . 

Multiline - Gets or sets a value indicating whether this is a multiline TextBox control. 

AcceptsReturn - Gets or sets a value indicating whether pressing ENTER in a multiline TextBox  control creates a new line of text in the control or activates the default button for the form. 

PasswordChar - Gets or sets the character used to mask characters of a password in a single-line  TextBox control.


  

TextLength 

Gets the length of text in the control. 

ScrollBars 

Gets or sets which scroll bars should appear in a multiline TextBox control. This property has values 

None, Horizontal, Vertical, Both 

Text - Gets or sets the current text in the TextBox. 

Visible - The Visible property sets a value that indicates whether the textbox should be displayed on  a Windows Form. 

WordWrap- Indicates whether a multiline text box control automatically wraps words to the beginning  of the next line when necessary. 

Methods 

AppendText- Appends text to the current text of a text box. 

Clear - Clears all text from the text box control. 

Copy - Copies the current selection in the text box to the Clipboard.  

Cut - Moves the current selection in the text box to the Clipboard

Paste - Replaces the current selection in the text box with the contents of the ClipboardResetText- Resets the Text property to its default value. 

ToString- Returns a string that represents the TextBoxBase control. 

Focus - Method to set focus to a TextBox Control. 

Events 

Click- When a textbox is clicked, a click event is called in the textbox control. 

BackColorChanged- It is found in the TextBox Control when the property value of the BackColoris changed. 

BorderStyleChanged- It is found in the TextBox Control when the value of the BorderStyle is  changed. 

CursorChanged- It is found in TextBox, when the textbox control is removed from the  Control.ControlCollection. 

FontChanged- It occurs when the property of the Font is changed. 

GetFocus- It is found in TextBox control to get the focus. 

MultilineChanged- It is found in a textbox control when the value of multiline changes.


  

Public Class Form1 

Private Sub Form1_Load(sender As Object, e As EventArgs) _  

Handles MyBase.Load 

' Set the caption bar text of the form.  

Me.Text = "Example of MessageBox" 

End Sub 

Private Sub btnMessage_Click(sender As Object, e As EventArgs) _  

Handles btnMessage.Click 

MessageBox.Show("Thank you " + txtName.Text + " from " + txtOrg.Text)  

End Sub 

End Class

Lable Properties, Methods and Events 

A label control is used to display descriptive text for the form in control.  

It does not participate in user input or keyboard or mouse events. 

We cannot rename labels at runtime. 

The labels are defined in the class System.Windows.Forms namespace. 

Properties 

AutoSize- an AutoSize property of label control is used to set or get a value if it is automatically  resized to display all its contents. 

Border Style- It is used to set the style of the border in the Windows form. 

TextAlign- It is used to set the alignment of text such as centre, bottom, top, left, or right. ForeColor- It is used to set the color of the text. 

Image- It is used to set the image to a label in Windows Form. 

ImageIndex- It is used to set the index value to a label control displayed on the Windows form. 

Methods 

GetPreferredSize- Retrieves the size of a rectangular area into which a control can be fitted.  Refresh- Forces the control to invalidate its client area and immediately redraw itself and any child  controls. 

Select- Activates the control. 

Show- Displays the control to the user. 

ToString- Returns a String that contains the name of the control. 


  

Events 

Click- Click event is occurring in the Label Control to perform a click. 

DoubleClick- When a user performs a double-clicked in the Label control, the DoubleClick event  occurs. 

GotFocus- Occurs when the control receives focus. 

TextChanged- Occurs when the Text property value changes. 

BackColorChanged- A BackColorChanged event occurs in the Label control when the value of the  BackColor property is changed. 

DragDrop- A DragDrop event occurs in the Label control when a drag and drop operation is  completed. 

Button Properties, Methods and Events 

Button control is used to perform a click event in Windows Forms, and it can be clicked by a mouse or  by pressing Enter keys. 

It is used to submit all queries of the form by clicking the submit button or transfer control to the next  form. 

Properties 

BackColor- It is used to set the background color of the Button in the Windows form. BackgroundImage- It is used to set the background image of the button control. ForeColor- It is used to set or get the foreground color of the button control. 

Image- It is used to set or gets the image on the button control that is displayed. 

Location- It is used to set the upper-left of the button control's coordinates relative to the upper-left corner in the windows form. 

Text- It is used to set the name of the button control in the windows form. 

TabIndex- It is used to set or get the tab order of the button control within the form. Methods 

GetPreferredSize- Retrieves the size of a rectangular area into which a control can be fitted. 

NotifyDefault- Notifies the Button whether it is the default button so that it can adjust its appearance  accordingly.


  

Select- Activates the control. 

ToString- Returns a String containing the name of the Component, if any. This method should not be  overridden. 

Events 

Click- A Click event is found in the button control when the control is clicked. 

DoubleClick- When the user makes a double click on the button, a double click event is found in the button control. 

GotFocus- Occurs when the control receives focus. 

BackColorChanged- A BackColorChaged event is found in button control when the Background property is changed. 

BackgroundImageChanged- A BackgoundImageChanged event is found in button control when the  value of the BackgoundImage property is changed. 

TextChanged- It is found in the button control when the value of the text property is changed. 

DragDrop- The DragDrop event is found in the button control when the drag and drop operation is completed in the Form. 

ListBox Properties, Methods and Events 

The ListBox represents a Windows control to display a list of items to a user. A user can select an  item from the list. It allows the programmer to add items at design time by using the properties  window or at the runtime. 

You can populate the list box items either from the properties window or at runtime. To add items to a  ListBox, select the ListBox control and get to the properties window, for the properties of this control.  Click the ellipses (...) button next to the Items property. This opens the String Collection Editor dialog  box, where you can enter the values one at a line. 

Properties – 

AllowSelection-Gets a value indicating whether the ListBox currently enables selection of list items. BorderStyle-Gets or sets the type of border drawn around the list box. 

ColumnWidth-Gets of sets the width of columns in a multicolumn list box. 

HorizontalScrollBar- Gets or sets the value indicating whether a horizontal scrollbar is displayed in  the list box. 

MultiColumn-Gets or sets a value indicating whether the list box supports multiple columns.  SelectedIndex-Gets or sets the zero-based index of the currently selected item in a list box.  SelectedItem-Gets or sets the currently selected item in the list box. 

SelectedItems-Gets a collection containing the currently selected items in the list box. 

SelectionMode - Gets or sets the method in which items are selected in the list box. This property has  values −


  

None, One, MultiSimple, MultiExtended. 

Methods 

BeginUpdate-Prevents the control from drawing until the EndUpdate method is called, while items  are added to the ListBox one at a time. 

ClearSelected-Unselects all items in the ListBox. 

Sort-As the name suggests, a Sort() method is used to arrange or sort the elements in the ListBox. 

Remove-It is used to remove an item from an item collection. However, we can remove items using the item name. 

FindStringExact-Finds the first item in the ListBox that exactly matches the specified string. OnSelectedIndexChanged-Raises the SelectedIndexChanged event.  

OnSelectedValueChanged-Raises the SelectedValueChanged event.  

Events 

Public Class Listbx 

Private Sub Listbx_Load(sender As Object, e As EventArgs) Handles MyBase.Load  Me.Text = "Example of ListBox" 

ListBox1.Items.Add("Earth")  

ListBox1.Items.Add("Mercury")  

ListBox1.Items.Add("Mars")  

ListBox1.Items.Add("Jupiter")  

ListBox1.Items.Add("Venus")  

ListBox1.Items.Add("Neptune")  

ListBox1.Items.Add("Uranus")  

Button1.Text = "Show"  

Button2.Text = "Exit" 

Label2.Text = "Select the solar system from the ListBox"  

End Sub 

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  Dim lt As String 

lt = ListBox1.Text 

MsgBox(" Selected Solar System is " & lt)  

End Sub


  

Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles List  Box1.SelectedIndexChanged 

Label1.Text = ListBox1.SelectedItem.ToString()  

End Sub 

Private Sub Button2_Click (sender As Object, e As EventArgs) Handles Button2.Click  End 

End Sub 

End Class 

Combobox Properties, Methods and Events 

The ComboBox control is used to display more than one item in a drop-down list. It is a combination  of Listbox and Textbox in which the user can input only one item. it also allows a user to select an  item from a drop-down list. 

Properties 

DataBinding- It is used to bind the data with a ComboBox Control. 

DataSource- It is used to get or set the data source for a ComboBox Control. MaxLength- It is used by the user to enter maximum characters in the editable area of the combo  box. 

SelectedItem- It is used to set or get the selected item in the ComboBox Control. Sorted- The Sorted property is used to sort all the items in the ComboBox by setting the value. 

Methods 

BeginUpdate- Prevents the control from drawing until the EndUpdate method is called, while items  are added to the combo box one at a time. 

EndUpdate- Resumes drawing of a combo box, after it was turned off by the BeginUpdate method. 

FindString 

Finds the first item in the combo box that starts with the string specified as an argument. FindStringExact 

Finds the first item in the combo box that exactly matches the specified string. 

SelectAll 

Selects all the text in the editable area of the combo box. 

Events 

DropDown 

Occurs when the drop-down portion of a combo box is displayed.


  

DropDownClosed 

Occurs when the drop-down portion of a combo box is no longer visible. 

DropDownStyleChanged 

Occurs when the DropDownStyle property of the ComboBox has changed. 

SelectedIndexChanged 

Occurs when the SelectedIndex property of a ComboBox control has changed. SelectionChangeCommitted 

Occurs when the selected item has changed and the change appears in the combo box. 

Public Class Form1 

Private Sub Form1_Load(sender As Object, e As EventArgsHandles MyBase.Load 

Me.Text = "Example Of Combobox"  

End Sub 

Private Sub Button1_Click(sender As Object, e As EventArgsHandles Button1.Click 

If ComboBox1.SelectedIndex > -1 Then  

Dim sindex As Integer 

sindex = ComboBox1.SelectedIndex  

Dim sitem As Object 

sitem = ComboBox1.SelectedItem  

ListBox1.Items.Add(sitem

End If  

End Sub 

Private Sub Button2_Click(sender As Object, e As EventArgs)  Handles Button2.Click 

ComboBox1.Items.Clear()  

ComboBox1.Items.Add("Safety")  

ComboBox1.Items.Add("Security")  

ComboBox1.Items.Add("Governance")  

ComboBox1.Items.Add("Education")  

ComboBox1.Items.Add("Roads")  

ComboBox1.Items.Add("Health")  

ComboBox1.Items.Add("Food for all")  

ComboBox1.Text = "Select from..." 

End Sub 

Private Sub Button3_Click(sender As Object, e As EventArgsComboBox1.Sorted = True 

End Sub 

Private Sub Button4_Click(sender As Object, e As EventArgs)  ComboBox1.Items.Clear() 

End Sub 

Private Sub ComboBox1_SelectedIndexChanged(sender As Object, As EventArgs)

Handles ListBox1.SelectedIndexChanged  

Label1.Text = ComboBox1.SelectedItem.ToString()


  

End Sub  

End Class

CheckBox Properties, Methods and Events 

The CheckBox control allows the user to set true/false or yes/no type options. The user can select or  deselect it. When a check box is selected it has the value True, and when it is cleared, it holds the  value False. 

Properties 

Appearance 

Gets or sets a value determining the appearance of the check box. 

AutoCheck 

Gets or sets a value indicating whether the Checked or CheckedState value and the appearance of  the control automatically change when the check box is selected. 

CheckAlign 

Gets or sets the horizontal and vertical alignment of the check mark on the check box. Checked 

Gets or sets a value indicating whether the check box is selected. 

CheckState 

Gets or sets the state of a check box. 

Text 

Gets or sets the caption of a check box. 

Methods 

OnCheckedChanged 

Raises the CheckedChanged event. 

OnCheckStateChanged 

Raises the CheckStateChanged event. 

OnClick 

Raises the OnClick event. 

Events 

CheckedChanged- The CheckedChanged event is found when the value of the checked property is  changed to CheckBox. 

DoubleClick- It occurs when the user performs a double click on the CheckBox control. 


  

CheckStateChanged- It occurs when the value of the CheckState property changes to the CheckBox  control. 

AppearanceChanged- It occurs when the property of the Appearance is changed to the CheckBox control. 

Public Class Checkbxvb 

Private Sub Checkbxvb_Load(sender As Object, e As EventArgs) Handles MyBase.Load  Me.Text = "CheckBox Example" 

Label1.Text = "Select the fruits name" 

CheckBox1.Text = "Apple" CheckBox2.Text = "Mango" CheckBox3.Text = "Banana"  CheckBox4.Text = "Orange"CheckBox5.Text = "Potato" CheckBox6.Text = "Tomato"Button1.Text = "  Submit" Button2.Text = "Close" 

End Sub 

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim fruit As Stri  ng fruit = " " 

If CheckBox1.Checked = True Then fruit = "Apple" End If 

If CheckBox2.Checked = True Then fruit = fruit & " Mango" End If  

If CheckBox3.Checked = True Then fruit = fruit & " Banana" End If  

If CheckBox4.Checked = True Then fruit = fruit & " Orange" End If 

If CheckBox5.Checked = True Then  

fruit = fruit & " Potato" 

End If 

If CheckBox6.Checked = True Then  

fruit = fruit & " Tomato" 

End If 

If fruit.Length <> 0 Then 

MsgBox(" Selected items " & fruit)  

End If 

CheckBox1.ThreeState = True  

End Sub 

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click  End 'terminate the program 

End Sub 

End Class 

PictureBox Properties, Methods and Events 

PictureBox control is used to display the images on Windows Form. The PictureBox control has an  image property that allows the user to set the image at runtime or design time.


  

Properties 

AllowDrop 

Specifies whether the picture box accepts data that a user drags on it. 

ErrorImage 

Gets or specifies an image to be displayed when an error occurs during the image-loading process or  if the image load is cancelled. 

Image 

Gets or sets the image that is displayed in the control. 

ImageLocation 

Gets or sets the path or the URL for the image displayed in the control. 

SizeMode 

Determines the size of the image to be displayed in the control. This property takes its value from the  PictureBoxSizeMode enumeration, which has values − 

Normal − the upper left corner of the image is placed at upper left part of the picture box StrechImage − allows stretching of the image 

AutoSize − allows resizing the picture box to the size of the image 

CenterImage − allows centering the image in the picture box 

Zoom − allows increasing or decreasing the image size to maintain the size ratio. TabIndex 

Gets or sets the tab index value. 

Text 

Gets or sets the text for the picture box. 

Methods 

CancelAsync 

Cancels an asynchronous image load. 

Load 

Displays an image in the picture box 

LoadAsync 

Loads image asynchronously. 

ToString 

Returns the string that represents the current picture box. 

Events 

Click


  

Occurs when the control is clicked. 

KeyUp 

Occurs when a key is released when the control has focus. 

KeyDown 

Occurs when a key is pressed when the control has focus. 

KeyPress 

Occurs when a key is pressed when the control has focus. 

Resize 

Occurs when the control is resized. 

Public Class Form1 

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 

' Set the caption bar text of the form.  

Me.Text = "PictureBoc Example" 

End Sub 

Private Sub Button1_Click(sender As Object, e As EventArgs)  Handles Button1.Click 

PictureBox1.ClientSize = New Size(300, 300)  

PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage End Sub  

End Class 

Radio Button Properties, Methods and Events 

The RadioButton is used to select one option from the number of choices. If we want to select only  one item from a related or group of items in the windows forms, we can use the radio button. The RadioButton is mutually exclusive that represents only one item is active and the remains  unchecked in the form. 

Properties  

Appearance 

Gets or sets a value determining the appearance of the radio button. 

AutoCheck 

Gets or sets a value indicating whether the Checked value and the appearance of the control  automatically change when the control is clicked. 

CheckAlign 

Gets or sets the location of the check box portion of the radio button. 

Checked 

Gets or sets a value indicating whether the control is checked. 

Text 

Gets or sets the caption for a radio button.


  

Methods 

Contains(Control)- The Contains() method is used to check if the defined control is available in the  RadioButton control. 

DefWndProc(Message)- It is used to send the specified message to the Window procedure. Focus()-The Focus() method is used to set the input focus to the window form's RadioButton control. GetAutoSizeMode()-It is used to return a value that represents how the control will operate when the  AutoSize property is enabled in the RadioButton control of the Window form. 

ResetText()-As the name suggests, a ResetText() method is used to reset the property of text to its default value or empty. 

Update()-It is used to reroute an invalid field, which causes control in the client region. Events 

AppearanceChanged 

Occurs when the value of the Appearance property of the RadioButton control is changed. CheckedChanged 

Occurs when the value of the Checked property of the RadioButton control is changed. 

Public Class RadioBtn 

Private Sub RadioBtn_Load(sender As Object, e As EventArgs) Handles MyBase.Load  Me.Text = "javaTpoint.com" ' Set the title of the form 

Label1.Text = "Select the Gender" 

RadioButton1.Text = "Male" ' Set the radiobutton1 and radiobutton2  

RadioButton2.Text = "Female" 

RadioButton3.Text = "Transgender"  

Button1.Text = "Submit" ' Set the button name 

Button2.Text = "Exit"  

End Sub 

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  Dim gen As String 

If RadioButton1.Checked = True Then  

gen = "Male" 

MsgBox(" Your gender is : " & gen) 

ElseIf RadioButton2.Checked = True Then  

gen = "Female" 

MsgBox(" Your gender is : " & gen)


  

Else 

gen = "Transgender" 

MsgBox(" You have Selected the gender : " & gen)  

End If 

End Sub 

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click  End 'Terminate the program 

End Sub  

End Class 

Panel 

The Panel control is a container control that is used to host a group of similar child controls. 

Panel control when you have to show and hide a group of controls. Instead of show and hide  individual controls, you can simply hide and show a single Panel and all child controls. 

Creating a Panel 

We can create a Panel control using the Forms designer at design-time or using the Panel class in  code at run- time. 

Design-time 

To create a Panel control at design-time, you simply drag and drop a Panel control from Toolbox to  a Form in Visual Studio. After you drag and drop a Panel on a Form, the Panel looks like Figure 1.  Once a Panel is on the Form, you can move it around and resize it using mouse and set its  properties and events. 

Run-time


  

Creating a Panel control at run-time is merely a work of creating an instance of Panel class, set its  properties and adds Panel class to the Form controls. 

First step to create a dynamic Panel is to create an instance of Panel class. The following code snippet  creates a Panel control object. 

Dim dynamicPanel As New Panel() 

In the next step, you may set properties of a Panel control. The following code snippet sets location, size  and Name properties of a Panel. 

dynamicPanel.Location = New  

System.Drawing.Point(26, 12) dynamicPanel.Name =  

"Panel1" 

dynamicPanel.Size = New  

System.Drawing.Size(228, 200)  

dynamicPanel.BackColor = Color.LightBlue 

Once the Panel control is ready with its properties, the next step is to add the Panel to a Form. To do so, we  use Form.Controls.Add method that adds Panel control to the Form controls and displays on the Form based  on the location and size of the control. The following code snippet adds a Panel control to the current Form. 

Controls.Add(dynamicPanel) 

Setting Panel Properties 

After you place a Panel control on a Form, the next step is to set its properties. 

The easiest way to set properties is from the Properties Window. You can open Properties window by pressing  F4 or right click on a control and select Properties menu item. 

The Panel control is a container control that is used to host a group of similar child controls. One of  the major uses I found for a Panel control when you have to show and hide a group of controls.  Instead of show and hide individual controls, you can simply hide and show a single Panel and all  child controls. 

In this article, we will demonstrate how to create and use a Panel control in a Windows Forms application. Creating a Panel 

We can create a Panel control using the Forms designer at design-time or using the Panel class in  code at run- time. 

Design-time 

To create a Panel control at design-time, you simply drag and drop a Panel control from Toolbox to  a Form in Visual Studio. After you drag and drop a Panel on a Form, the Panel looks like Figure 1. Once a Panel is on the Form, you can move it around and resize it using mouse and set its  properties and events.


  

Figure 1 

Run-time 

Creating a Panel control at run-time is merely a work of creating an instance of Panel class, set its  properties and adds Panel class to the Form controls. 

First step to create a dynamic Panel is to create an instance of Panel class. The following code  snippet creates a Panel control object. 

Dim dynamicPanel As New Panel() 

In the next step, you may set properties of a Panel control. The following code snippet sets  location, size and Name properties of a Panel. 

dynamicPanel.Location = New  

System.Drawing.Point(26, 12) dynamicPanel.Name =  

"Panel1" 

dynamicPanel.Size = New  

System.Drawing.Size(228, 200)  

dynamicPanel.BackColor = Color.LightBlue 

Once the Panel control is ready with its properties, the next step is to add the Panel to a  Form. To do so, we use Form.Controls.Add method that adds Panel control to the Form  controls and displays on the Form based on the location and size of the control. The  following code snippet adds a Panel control to the current Form. 

Controls.Add(dynamicPanel) 

Setting Panel Properties 

After you place a Panel control on a Form, the next step is to set its properties.


  

The easiest way to set properties is from the Properties Window. You can open Properties window by pressing  F4 or right click on a control and select Properties menu item. The Properties window looks like Figure 2. 

Figure 2 

Panel has most of the common control properties. Here I am going to discuss the main purpose of a Panel. Adding Controls to a Panel 

You can add controls to a Panel by dragging and dropping control to the Panel. We can add  controls to a Panel at run-time by using its Add method. The following code snippet creates  a Panel, creates a TextBox and a CheckBox and adds these two controls to a Panel. 

Private Sub CreateButton_Click(ByVal sender As System.Object, ByVal e As  System.EventArgs) Handl es CreateButton.Click 

Dim dynamicPanel As New Panel() 

dynamicPanel.Location = New  

System.Drawing.Point(26, 12) dynamicPanel.Name =  

"Panel1" 

dynamicPanel.Size = New  

System.Drawing.Size(228, 200)  

dynamicPanel.BackColor = Color.LightBlue 

Dim textBox1 As New TextBox()  

textBox1.Location = New Point(10,  

10)


  

textBox1.Text = "I am a  

TextBox5" textBox1.Size =  

New Size(200, 30) 

Dim checkBox1 As New CheckBox()  

checkBox1.Location = New Point(10,  

50) checkBox1.Text = "Check Me"  

checkBox1.Size = New Size(200,  

30) 

dynamicPanel.Controls.Add(textBox 

1)  

dynamicPanel.Controls.Add(checkB 

ox1) 

Controls.Add(dynamicPan 

el) End Sub 

Show and Hide a Panel 

I have seen in many applications when you want to show and hide a group of controls on a Form based on some  condition. That is where a Panel is useful. Instead of show and hide individual controls, we can group controls  that we want to show and hide and place them on two different Panels and show and hide the Panels. To show  and hide a Panel, we use Visible property. 

dynamicPanel.Visible = False 

Scroll Bar 

The ScrollBar controls display vertical and horizontal scroll bars on the form. This is used for  navigating through large amount of information. There are two types of scroll bar controls: HScrollBar for horizontal scroll bars and VScrollBar for vertical scroll bars. These are used  independently from each other. 

Properties 

AutoSize 

Gets or sets a value indicating whether the ScrollBar is automatically resized to fit its contents. BackColor 

Gets or sets the background color for the control. 

ForeColor 

Gets or sets the foreground color of the scroll bar control. 

ImeMode 

Gets or sets the Input Method Editor (IME) mode supported by this control. 

Maximum 

Gets or sets the upper limit of values of the scrollable range. 

Minimum 

Gets or sets the lower limit of values of the scrollable range. 

Value 

Gets or sets a numeric value that represents the current position of the scroll box on the scroll bar  control.


  

Methods 

UpdateScrollInfo- It is used to update the ScrollBar control using the Minimum, maximum, and the  value of LargeChange properties. 

OnScroll(ScrollEventArgs)- It is used to raise the Scroll event in the ScrollBar Control. OnEnabledChanged- It is used to raise the EnabledChanged event in the ScrollBar control. Select- It is used to activate or start the ScrollBar control. 

Events 

Click 

Occurs when the control is clicked. 

DoubleClick 

Occurs when the user double-clicks the control. 

Scroll 

Occurs when the control is moved. 

ValueChanged 

Occurs when the Value property changes, either by handling the Scroll event or programmatically. 

Public Class ScrollBar 

Private Sub ScrollBar_Load(sender As Object, e As EventArgs) Handles MyBase.Load  Me.Text = "Example of Scroll Bar" 'Set the title for a Windows Form 

Label1.Text = "Use of ScrollBar in Windows Form"  

Label1.ForeColor = Color.Blue 

Me.AutoScroll = True  

Me.VScrollBar1.Minimum =

Me.VScrollBar1.Maximum = 100 

Me.VScrollBar1.Value = 0  

Me.VScrollBar1.BackColor = Color.Blue  

Me.HScrollBar1.Minimum =

Me.HScrollBar1.Maximum = 100 

Me.HScrollBar1.Value = 35  

End Sub 

End Class


  

Timer 

Timer Control plays an important role in the Client side programming and Server side programming,  also used in Windows Services. By using this Timer Control, windows allow you to control when  actions take place without the interaction of another thread. 

We can use Timer Control in many situations in our development environment. 

If you want to run some code after a certain interval of time continuously, you can use the Timer  control. 

As well as to start a process at a fixed time schedule, to increase or decrease the speed in an  animation graphics with time schedule etc.you can use the Timer Control. 

At runtime it does not have a visual representation and works as a component in the background.  we can control programs in millisecond, seconds, minutes and even in hours. The Timer Control allows us to set Interval property in milliseconds 

(1 second is equal to 1000 milliseconds). 

For example, if we want to set an interval of two minute we set the value at Interval property as 120000,  means 120x1000 . 

The Timer Control starts its functioning only after its Enabled property is set to True, by default Enabled  property is False. 

Public Class Form1 

Dim second As Integer 

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles  MyBase.Load 

Timer1.Interval = 1000 

Timer1.Start() 'Timer starts functioning  

End Sub 

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles  Timer1.Tick 

Label1.Text = DateTime.Now.ToString 

second = second + 1  

If second >= 10 Then 

Timer1.Stop() 'Timer stops functioning  

MsgBox("Timer Stopped ...") 

End If  

End Sub 

End Class 

List View 

The ListView Controls are used to display a collection of items in the Windows Forms. It uses one of  the view lists, such as LargeIcon, SmallIcon, Details, List, and Tile. Furthermore, the ListViewallows  the user to add or remove icons from the ListView Control.


  

Properties 

Alignment 

Gets or sets the alignment of items in the control. 

BackColor 

Gets or sets the background color. 

CheckBoxes 

Gets or sets a value indicating whether a check box appears next to each item in the control. CheckedItems 

Gets the currently checked items in the control. 

Items 

Gets a collection containing all items in the control. 

Scrollable 

Gets or sets a value indicating whether a scroll bar is added to the control when there is not enough  room to display all items. 

View 

Gets or sets how items are displayed in the control. This property has the following values: 

LargeIcon − displays large items with a large 32 x 32 pixels icon. 

SmallIcon − displays items with a small 16 x 16 pixels icon 

List − displays small icons always in one column 

Details − displays items in multiple columns with column headers and fields Tile − displays items as full-size icons with item labels and sub-item information. 

Methods 

ArrangeIcons()-The ArrangeIcons method is used to arrange all the items displayed as icons in the  ListView control. 

FindItemWithText()-It is used to search the first ListViewItem that started with the given text value. GetItemAt()-The GetItemAt method is used to get an item at the specified location of the ListView  control. 

Clear()- The Clear method is used to clear all the items and columns from the ListView control. Sort() - The Sort method is used to sort items of the ListView. 

Events 

ItemActivate- the Item Activate event occurred when an item activated in the List View control. ItemChecked- the Item Checked event is found in the List View control when the checked state of an item changes. 

TextChanged- Occurs when the Text property is changed.


  

ItemCheck 

Occurs when an item in the control is checked or unchecked. 

AfterLabelEditEvent- It occurs when the user in the ListView control edits the label for an item. 

Public Class List_View 

Private Sub List_View_Load(sender As Object, e As EventArgs) Handles MyBase.Load  Me.Text = "Example Of ListVIew" 'Set the title for the Windows form 

ListView1.View = View.Details ' Display the List in details  

ListView1.GridLines = True ' Set the Grid lines  

Label1.Text = "Enter the Roll No." ' Set the name of Labels  

Label2.Text = "Enter Your Name" 

Label3.Text = "Enter Your Email"  

Label4.Text = "Enter the Course"  

Label5.Text = "Student details" 

ListView1.Columns.Add("Roll No", 70, HorizontalAlignment.Left) ' set the name of column  ListView1.Columns.Add("Name", 100, HorizontalAlignment.Left) ' set the name of column  ListView1.Columns.Add("Email", 150, HorizontalAlignment.Left) ' set the name of column  ListView1.Columns.Add("Course", 100, HorizontalAlignment.Left) ' set the name of column  

ListView1.BackColor = Color.LightSkyBlue 

Button1.Text = "Add New Entry"  

Button1.ForeColor = Color.White  

Button1.BackColor = Color.Green  

Label5.ForeColor = Color.Red  

Button2.Text = "Exit"  

Button2.BackColor = Color.Red 

End Sub 

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  Dim str(4) As String 

Dim itm As ListViewItem 

str(0) = TextBox1.Text 'Accept value from the user.  

str(1) = TextBox2.Text 

str(2) = TextBox3.Text  

str(3) = TextBox4.Text 

itm = New ListViewItem(str) 

ListView1.Items.Add(itm) 'Add the items into the ListView  

End Sub 

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click


  

End 'Exit from the program  

End Sub 

End Class 

Tree View 

The TreeView control is used to display a hierarchical representation of the same data in a tree  structure. The top-level in the tree view is the root node with one or more child nodes. In addition, the  root node can be contracted or expanded by clicking on the plus sign (+) button. It is also useful to  provide the full path of the root node to the child node. 

Properties 

BackColor 

Gets or sets the background color for the control. 

BackgroundImage 

Gets or set the background image for the TreeView control. 

BackgroundImageLayout 

Gets or sets the layout of the background image for the TreeView control. 

BorderStyle 

Gets or sets the border style of the tree view control. 

VisibleCount 

Gets the number of tree nodes that can be fully visible in the tree view control. 

Method 

CollapseAll 

Collapses all the nodes including all child nodes in the tree view control. 

ExpandAll 

Expands all the nodes. 

GetNodeAt 

Gets the node at the specified location. 

GetNodeCount 

Gets the number of tree nodes. 

Sort 

Sorts all the items in the tree view control

Events


  

AfterCheck 

Occurs after the tree node check box is checked. 

AfterCollapse 

Occurs after the tree node is collapsed. 

AfterExpand 

Occurs after the tree node is expanded. 

AfterSelect 

Occurs after the tree node is selected. 

Paint 

Occurs when the TreeView is drawn. 

The TreeNode Class 

The TreeNode class represents a node of a TreeView. Each node in a TreeView control is an object  of the TreeNode class. To be able to use a TreeView control we need to have a look at some  commonly used properties and methods of the TreeNode class. 

Properties 

Name 

Gets or sets the name of the tree node. 

Text 

Gets or sets the text displayed in the label of the tree node. 

ToolTipText 

Gets or sets the text that appears when the mouse pointer hovers over a TreeNode. 

Methods 

Collapse 

Collapses the tree node. 

Expand 

Expands the tree node. 

ExpandAll 

Expands all the child tree nodes. 

Remove 

Removes the current tree node from the tree view control.


  

ToolBar 

The Windows Forms ToolBar control is used on forms as a control bar that displays a row of drop down menus and bitmapped buttons that activate commands. 

a toolbar contains buttons and menus that correspond to items in an application's menu structure,  providing quick access to an application's most frequently used functions and commands. 

A ToolBar control is usually "docked" along the top of its parent window, but it can also be docked to  any side of the window. A toolbar can display tooltips when the user points the mouse pointer at a  toolbar button. A ToolTip is a small pop-up window that briefly describes the button or menu's  purpose. To display ToolTips 

The ToolBar control allows you to create toolbars by adding Button objects to a Buttons collection.  You can use the Collection Editor to add buttons to a ToolBar control; each Button object should have  text or an image assigned, although you can assign both. The image is supplied by an associated ImageList component. 

Status Bar 

A status bar is commonly used to provide hints for the selected item or information about an action  currently being performed on a dialog. Normally, the StatusBar is placed at the bottom of the screen,  as it is in MS Office applications and Paint, but it can be located anywhere you like. 

Properties 

BackgroundImage- It is possible to assign an image to the status bar that will be drawn in the background. 

Panels- This is the collection of panels in the status bar. Use this collection to add and remove panels. 

ShowPanels- If you want to display panels, this property must be set to true. 

Text-set text on status bar. 

Open File Dialog 

The OpenFileDialog control prompts the user to open a file and allows the user to select a file to  open. The user can check if the file exists and then open it. The OpenFileDialog control class inherits  from the abstract class FileDialog

If the ShowReadOnly property is set to True, then a read-only check box appears in the dialog box.  You can also set the ReadOnlyChecked property to True, so that the read-only check box appears  checked.

  

Public Class OpenFIleDialog 

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

If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then  

OpenFileDialog1.InitialDirectory = "C:\" 

OpenFileDialog1.Title = "Open Image File"  

OpenFileDialog1.Filter = "Image|*jpg" 

PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)  

Label2.Text = OpenFileDialog1.FileName 

End If  

End Sub 

End Class 

Save File Dialog 

The SaveFileDialog control prompts the user to select a location for saving a file and allows the user  to specify the name of the file to save data. The SaveFileDialog control class inherits from the  abstract class FileDialog. 

Public Class SaveFileDialog 

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

SaveFileDialog1.Filter = "TXT Files(*txt*)|*.txt

If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then  My.Computer.FileSystem.WriteAllText(SaveFileDialog1.FileName

RichTextBox1.Text, True

RichTextBox1.Clear() 

End If  

End Sub 

End Class



 

Font Dialog 

The Font Dialog Box allows the user to select the font family, style, and size for the text in an  application. However, a user can also select the font color and apply the current setting to the  selected text of the control by clicking the Apply button

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles  Button2.Click 

FontDialog1.ShowColor = True 

If FontDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then  

RichTextBox1.Font = FontDialog1.Font 'Change the font of the selected string  

RichTextBox1.ForeColor = FontDialog1.Color 'Change the color of selected string End If  

End Sub 

Color Dialog 

The Color Dialog box is used to display the Color dialog box and the selection of colors on the  Microsoft Windows Application. It allows users to set or change the color of an object, such as the  background color of a control or the color used to paint an object. Furthermore, the control dialog box  also allows the facility to the user to create a new color by mixing all other colors of the Color Dialog  Box.


 

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles  Button3.Click 

ColorDialog1.FullOpen = False 

If ColorDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then  

RichTextBox1.ForeColor = ColorDialog1.Color 

End If 

'Me.BackColor = ColorDialog1.Color 'Change Background color of the form  

End Sub 

Print Dialog 

The PrintDialog control lets the user to print documents by selecting a printer and choosing which  sections of the document to print from a Windows Forms application. 

There are various other controls related to printing of documents. Let us have a brief look at these  controls and their purpose. These other controls are − 

The PrintDocument control − it provides support for actual events and operations of printing  in Visual Basic and sets the properties for printing. 

The PrinterSettings control − it is used to configure how a document is printed by specifying  the printer. 

The PageSetUpDialog control − it allows the user to specify page-related print settings  including page orientation, paper size and margin size. 

The PrintPreviewControl control − it represents the raw preview part of print previewing from  a Windows Forms application, without any dialog boxes or buttons. 

The PrintPreviewDialog control − it represents a dialog box form that contains a  PrintPreviewControl for printing from a Windows Forms application.

  

Private Sub printpriview_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)  Handles Button5.Click 

If RichTextBox1.Text = "" Then  

MsgBox("Please write some text...") 

Else 

PrintPreviewDialog1.ShowDialog()  

End If 

End Sub 

Private Sub print_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles  Button4.Click 

If PrintDialog1.ShowDialog = DialogResult.OK Then 'Open the print dialog box  PrintDocument1.PrinterSettings = PrintDialog1.PrinterSettings  

PrintDocument1.Print() 'print a document 

End If  

End Sub 

Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As  System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage Dim font As New Font("Times New Roman", 10, FontStyle.Bold) 'set the font to display  e.Graphics.DrawString(RichTextBox1.Text, font, Brushes.Red, 100, 100) 

End Sub 

Private Sub Form_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles  MyBase.Load 

PrintPreviewDialog1.Document = PrintDocument1  

End Sub 

Link Lable 

A LinkLabel control is a label control that can display a hyperlink. A LinkLabel control is inherited from  the Label class so it has all the functionality provided by the Windows Forms Label control. LinkLabel  control does not participate in user input or capture mouse or keyboard events. 

Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As  System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked 

System.Diagnostics.Process.Start("www.google.com")  

End Sub 

Designing menus: 

A menu is used as a menu bar in the Windows form that contains a list of related commands, and it is  implemented through MenuStrip Control. The Menu control is also known as the  VB.NET MenuStrip Control. The menu items are created with ToolStripMenuItem Objects.  Furthermore, the ToolStripDropDownMenu and ToolStripMenuItem objects enable full control over  the structure, appearance, functionalities to create menu items, submenus, and drop-down menus 

Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As  System.EventArgs) Handles ExitToolStripMenuItem.Click 

Me.Dispose()  

End Sub



 

Private Sub NewToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As  System.EventArgs) Handles NewToolStripMenuItem.Click 

Dim f1 As New ChkBoxForm()  

f1.Visible = True 

End Sub 

Context menu: 

The ContextMenuStrip control represents a shortcut menu that pops up over controls, usually when  you right click them. They appear in context of some specific controls, so are called context menus.  For example, Cut, Copy or Paste options. 

This control associates the context menu with other menu items by setting that menu item's  ContextMenuStrip property to the ContextMenuStrip control you designed. 

Context menu items can also be disabled, hidden or deleted. You can also show a context menu with  the help of the Show method of the ContextMenuStrip control. 

Private Sub CutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As  System.EventArgs) Handles CutToolStripMenuItem.Click 

RichTextBox1.Cut()  

End Sub 

Private Sub CopyToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As  System.EventArgs) Handles CopyToolStripMenuItem.Click 

RichTextBox1.Copy()  

End Sub 

Private Sub PasteToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As  System.EventArgs) Handles PasteToolStripMenuItem.Click 

RichTextBox1.Paste()  

End Sub 

Access & shortcut keys 

The ToolStripMenuItem class supports the menus and menu items in a menu system. You  handle these menu items through the click events in a menu system. 

Set Access Keys for Menu Items 

Setting access keys for a menu allows a user to select it from the keyboard by using the ALT key. 

For example, if you want to set an access key ALT + F for the file menu, change its Text with an added  & (ampersand) preceding the access key letter. In other words, you change the text property of the file  menu to &File.


 

Set Shortcut Keys for Menu Items 

When you set a shortcut key for a menu item, user can press the shortcut from the keyboard and it  would result in occurrence of the Click event of the menu. 

A shortcut key is set for a menu item using the ShortcutKeys property. For example, to set a shortcut  key CTRL + E, for the Edit menu − 

Select the Edit menu item and select its ShortcutKeys property in the properties window. Click the drop down button next to it. 

Select Ctrl as Modifier and E as the key. 

The End


No comments:

Post a Comment