0% found this document useful (0 votes)
150 views

Unit 3 - Introduction To Windows Controlss

Uploaded by

devanshi88888888
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
150 views

Unit 3 - Introduction To Windows Controlss

Uploaded by

devanshi88888888
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 45
404- NET Programming Unit -3. Introduction to Windows Controls 3.1, Working with Too! Box Controls 3.1.1, Common controls - Label, Text Box, Button, Check Box, Radio Button, Date Time Picker, List Box, Combo box, Picture Box, Rich Text Box, Tree View, Tool Tip, Progress bar, Masked Text box, Notify Leon, Link Label, Checked List box 3.1.2. Container Controls 3.1.3. Data - Data Set, Data Grid (Discuss in Unit) 3.1.4, Component Controls Image lst, errr provider, Help provider, Timer 3.2, Working with Menus and Dialogue Boxes 3.3. Exception Handling 3.1. Structured Error Handling 3.3.2, Unstructured Error Handling > VB.NET Form + 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. + Itis like a container for holding different control that allows the user fo interact with an application, * The controls are an object in a form such as buttons, Textboxes, Textarea, labels, et. to perform, some action. However, we can add any control to the runtime by eteating an instance of it, + 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. * VB.NET Form Properties * The following are the most important list of properties related to a form, And these properties can be set or read while the application is being executed, Properties Description BackColor It is used to set the background color for the form, BackgroundImage/[ is used to set the background image of the form. (Cursor It is used to set the cursor image when it hovers over the form, ‘Font It is used to get or set the font used in a form, Locked it determines whether the form is locked or not ‘FormBorderStyle_|lt is used to set or get border style in a form, Text It is used to set the tile for a form window. fapicana if itenedtoeuthercate whether for is a cominr of « Muiple DoeunentInerfiee (MDD ‘Autoseroll [allows whether to enable auto-scrolling in a form. ‘AcceptButton [It is used to set the form button if the enter key is pressed. Name vis used to define the name of the form. Enabled It uses the True or False value to enable mouse or keyboard events in the form, rope it uses a Boolean value that represents whether you want to put the window form on top of the jother form. By default, itis False. © scanned wth oxen Seamer 404-.NET Programming © Form Events The following are the most important list of events related to a form, Events Description [Activated [An activated even is found when the wer or program aatvales the form. Click A lick event is ative when the form s clicked. Closed [A closed even is found before closing the fom Closing Itexiss when a forms closing. ‘ [DoubleClick DoubleClick: |The DoubleClick event is activated when a user double clicks on the form. DragDrop [A DragDrop event is activated wien a drag and drop operation is performed MouseDowa [+MouseDown event asivated when de mouse pointers on the frm, andthe mouse bation is pressed (GoiFocus [A GoiFocus event is activated when te form contol reeives a foo: [HelpButionClicked[I is activated when a user clicked onthe help button, KeyDown [A KeyDown event is activated when a key is pressed while focusing onthe form: iKeyUp [A KeyUp even i activated when a key is released while focusing onthe form. Load [The load event is used to load a form before itis ist displayed LastFocus kis activated when he form loses fous [MouseEnter JA MouseEnter event is activated when the mouse pointer enter he fom. [MouseHfover JA Mouseover events activated vhen the mouse ponte put on the form [MouseLeaye [A Mouse.cave event is activated when the mouse pointer leaves the form surfs. Shown tis activated whenever the form s displayed forthe fst ime. Sera [A Serol event is activated when a form sserolled through a wer or code Resize [A Resize event i ctvated when a form is resized Move [A Move creat ia activated when a form is moved For creating a Windows Forms application in VB.NET, we need to follow the following steps in Microsoft Visual Studio. 1. GoTo File Menu, 2. Click on New Project. 3. Click on Windows Forms App or Application ‘And finally, cick on the ‘Create’ button to ereate your project, and then, it displays the following window form ‘with a name Form. © scanned wth oxen Seamer 404-.NET Programming 3.1. Working with Tool Box Controls © What is Control? = A control is an object that can be drawn on to the Form. = Mainly controls are visible object. = The controls are to enable or enhance user Interaction with the application, = Examples of these controls are TextBox, Bution, Checkbox,Label, Timer, TreeView, etc. = All controls are unique with through its features, = All the controls have properties, methods, and events. = Control class is the base class of all the windows controls. = We can work with controls in two ways: 1. Atdesign time 2. Atruntime. = We can add controls from the Toolbox at design time as given below: 1, Dragging and dropping 2. Double click on the control We can set their properties in the properties window = We can add controls at runtime as given steps below: 1. Create an object of Contra, 2. Set the properties of it 3. Add that controls to the form using Me-Controls.Add(Object name) Example: Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim txt As New Textliox Dim bin As New Button With ext Tent ForeColor = Color.Red BackColor = Color.Gold Name ="txtno" Top = 10 Left = 10 ‘Width = 150 End With With bin Color.Green Color.BurlyWood Me.Controls.Add(tst) Me.Controls.Adai(oin) End Sub * With.....—End With Statement + In VB.NET, the With End statement is not the same as a loop structure. It is used to access and execute statements on a specified object without specifying the name of the objects ‘with each statement ‘Within a With statement block, you can specify a member of an object that begins with a period (.) to define ‘multiple statements, Syntax: With objExpression [ Statements to be Executed] End With objExpression: It defines the data type of objExpression. It may be any class or structure type or basic Statement: It defines one or more executed statements within the With block Example: ‘AS Above © scanned wth oxen Seamer 404- NET Programming ‘+ Some common properties of the controls are as given below: Property Description BackColor Gets/Sets the background color Backgroundimage _Gets/Sets the background image ContextMenu Gets/Sets the shortcut menu for the control Cursor Gets/Sets the cursor to be displayed when the user moves the mouse over the form Enabled Gets/Sets a value indicating ifthe control is enabled Font Gets/Sets the font for the control ForeColor Gets/Sets the font color (foreground) of the control Height Gets/Sets the height of the control Left Gets/Sets the x-coordinates ofa control's left edge in pixels Location Gets/Sets the co-ordinates of the upper-left comer of the control Locked Gets/Sets the resize or move the control at design time. Name Gets/Sets name for the control Right Returns the distance between the right edge of the control and the left ‘edge of its container Size Gets/Sets size of the control in pixels Tablndex Gets/Sets the tab order of this control in its container TabStop Gets/Sets a value specifying ifthe user can Tab or shift+Tab to this control with the tab key Text Gets/Sets the text for this control Top Gets/Sets the top coordinates of the control Visible Gets/Sets a value for visibility of the control Width Gets/Sets the width of the control ‘+ Some common events of the controls areas given below: Event Descripti Click Occurs when the control is elicked. GotFocus ‘Occurs when the control receives focus. KeyDown ‘Occurs when a key is pressed while the control has focus. KeyPress Occurs when a key is pressed while the control has focus. Key Up ‘Occurs when a key is released while the control has focus, LostFocus Occurs when the control loses focus MouseClick Occurs when the control is clicked by the mouse, MouseDown ‘Occurs when the mouse pointer is over the control and a mouse button is pressed MouseEnter ‘Occurs when the mouse pointer enters the control. MouseHover ‘Occurs when the mouse pointer rests on the control MouseLeave ‘Occurs when the mouse pointer leaves the control MouseMove ‘Occurs when the mouse pointer is moved over the contro. Mouse Up ‘Occurs when the mouse pointer is over the control and a mouse button is released © scanned wth oxen Seamer 404-.NET Programming 3.1.1 Common Controls Pinter Button CheckBox CCheckedListBox ComboBox DateTimePicker Label LinkLabel ListBox ListView MaskesTetBox MonthCalendar Notifyicon NumericUpDown PictureBox ProgressBar RadieButton RichTextBox TextBox Toottip TreeView © Label WebBrowser + In VB.NET, a label control is used to display descriptive text. + Itdoes not participate in user input or keyboard or mouse events + Also, we cannot rename label at runtime. +The labels are defined in the class System. Windows.Forms namespace. ifo>>amniee- VB.NET Label Properties Properties Description [As the name defines, an AutoSize property of label control is used to sel or get a value if tis [Antosize automatically resized to display al its contents [Border Style Its used to set the siyle ofthe border inthe Windows form. PreferredWidth|I is used to set or gt the prefered width for dhe Label control Font itis used to get or set the font ofthe text displayed on a Windows form. DPreferredHteigh|t is used to set the beigt for the Label Control FTextAlign __ |[vis wsedo se the alignment of ext such as centre, bottom, top Tel o Fight. [ForeColor |v is used 10 set the color of the text. [Text [tis used 10 set the name ofa label inthe Windows Form. ‘ontextMenu is use 1o get or sets the shortcut menu associated withthe Label control [DefauleSize |v is used to get the default size of the Label control Image [is used to set the image toa label in Windows Form, [imagelndex ft is used to se the index value toa label control displayed on the Windows form. © scanned wth oxen Seamer 404- NET Programming VB.NET Label Events Evens Description eure eases! ‘event occurs in the Label control when the value of AutoSize property is [ctiek [Click event is occurring in the Label Control to perform a click. [DoubleClick __| When a user performs a double-clicked inthe Label control, the DoubleClick event occurs. [GotFocus [it occurs when the Label Control receives focus on the Window Form. [Leave [The Leave event is found when the input focus leaves the Label Control [TabIndexChanged It occurs when the value of Tabindex property is changed in the Label control 'When the control is removed from the Control, ControlCollection, a ControlRemoved event, [FabStopChanged | It occurs when the property of TabStop is changed in the Label Control. VA BackColorChanged event oceurs in the Label control when the value of the BackColor property |ControlRemoved [BackColorChanged ed [ControtAdded | When a new control is added to the Control, ConirolCollection, a ControlAdded event occurs. [DragDrop [A DragDrop event occurs in the Label control when a drag and drop operation is completed. ‘Text Box TextBoxes are used to accept input from the user or used to display text. + They are sometimes called an edit field or edit control. + Typically, a TextBox control is used to display, or accept as input singe line of text + TextBox can display multiple lines. + TextBox control ean work as a Password input control By default, a TextBox holds up to 32767 characters, but when displaying multiple lines, a text box holds up to 2GB of text + TextBox can be read-only, + The prefix ofthe TextBox is "txt" TextBox demo © scanned wth oxen Seamer 404- NET Programming Properties Description It is used to get or seta valuc that indicates how the automatic completion works for the textbox |AutoCompleteMode| control [Front itis used to set the font style of the text displayed on a Windows form [Lines itis used to set the number of lines in a TextBox control. ic is used to get or seta value representing whether the TextBox control can modify the {character's case as they typed. it is used to enter more than one line in a TextBox control, by changing the Multiline property |CharacterCasing pastas Wvalue from False to True. [pccepsetura |S 86410 ge or sea value that indica whether pressing he eter baton naming textbox: it creates a new line of text in control, [PasswordChar Iv is used to set the password character that can be a mask ina singe line of a TextBox contol |PreferredHeight [lc is used to set the preferred height of the textbox control in the window form [SerouBars itis used to display a scrollbar on a multiline textbox by setting a value for a Textbox control [rext It is used to get or set the text associated withthe textbox control [The Visible property sets a value that indicates whether the textbox should be displayed on a vines {Windows Form, [The WordWrap properties validate whether the multiline Textbox control automatically wraps peta |words to the beginning of the next line when necessary. VB.NET TextBox Events ew = [Click When a textbox is clicked, a click event is called in the textbox control. [CausesValidationChangedit ours inthe TexiBox Control when the value of CaseValdaton property is changed DnecspeiakCeaged [is Toad inte Tantleronaed wheat repay valonal he Kamei lanpel BackCatorChanged —|lvs found nthe TextBox Control when the property vale ofthe BackColor i hanged BorderStleChanged ls found inthe TextBox Control when te value of the Bordriyle i changed [ContrtAdaea Tis found when the new conta added othe Control ConralCalleaion {tis found in TextBox, when the textbox control is removed from the [CursorChanged ‘Control, ControiCollection. [FontChanged Tr occurs when the property ofthe Font is changed. [GetFocus 11s found in TextBox control to get the focus [MouseClick ‘A MouseClick event occurs when the mouse elicks the control. [MultiineChanged Tris found ina textbox control when the value of multiline changes. Button ‘= 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. ‘= Itis used to submit all queries of the form by clicking the submit button or transfer control to the next form. However, we can set the buttons on the form by using drag and drop operation © scanned wth oxen Seamer 404- NET Programming VB.NET Button Properties Properties Description | aaameenIaae les ise Wooo tee Saas mug wl te bon cen iota [BackColor [cis used to set the background color of the Button in the Windows form. [Backgroundimagel[t is used to set the background image of the button control. [ForeColor [ts 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. ; it is used to set the upper-left ofthe button control's coordinates relative to the upper-left corner in [Location {the windows form. [rext itis used to set the name of the button control in the windows form, [Kania it is used to set or get a value representing whether the button control can accept data that can be ldragged by the user on the form. [TabIndex It is used to set or get the tab order of the button control within the form. VB.NET Button Events [A BackColorChaged event is found in button control when the Background property is [BackColorChanged = ackeroundImageChangeal BakeoundlmageChanged event is Found in button control when the value ofthe [BackeroundimageChangedlp.ackgoundimage property is changed [Click [A Click event is found in the bution control when the control is clicked [ContextMianuChanged itis found in button contol when the value of the ContextMenu property is changed. (eeicsihiided [A ControlA dded event is found in button control when a new control is added 0 the (Control, ControlCollection. ICursorChanged E,Cuehanged eves Tounin buon conto when he value ofthe contol is [When the user makes a double click on the button, a double click event is found in the PBoableCuet [button control, [rextChanged is found in the button control when the value ofthe text property is changed [The DragDrop event i found in the button control when the drag and drop operation is [PragDrop completed in the Form. Example: == I) © scanned wth oxen Seamer 404- NET Programming Code: Display button click event code: MsgBox("FirsiName:" & TextBox1.Text & vbCrLP& "Password:" & TextBox2.Text & VOCTLE& "Address:” & TextBox3 Text) Clear Button Click Event code: TextBoxl.Text =" TextBox2.Text =" TextBox3.Text =" Check Box = A-checkbox is clicked to select and clicked again to deselect some option. = When a checkbox is checked a check (a tick mark) appears indicating a selection, + Wecan use CheckBox controls in groups to display multiple choices from which the user can select one or = The difference between CheckBox and RadioButton is: Any number of CheckBox controls on a form can be selected and only one RadioButton in a group can be selected. Here are some properties of the VB.NET CheckBox control. Property Description [Default lt is used to get the default size of the checkbox [The AutoCheck property is used to check whether the checked value or appearance of control can be ‘automatically changed when the user clicked on the CheckBox control. [Check Align] is used to set the checkmark’s alignment, such as horizontal ot vertieal on the checkbox, [Appearance| The Appearance property is used to display the appearance of a checkbox control by setting a value [CheckState |The CheckState property is used to verify whether the checkbox status is checked in the window form. [The ThreeState property is used to check whether the control allows one to set three check positions instead of two by setting values, [FlatStyle _ [lt is used to obtain or set the Mlat appearance of a checkbox. [AutoCheck [Threestate CheckBox Methods ‘There are some Methods of the VB.NET CheckBox control, Method Description onClick [The OnClick method is used to fetch the Click event in the CheckBox control. [OnCheckStateChanged lt is used to call the CheckStateChanged event in the CheckBox control [ToString [The ToString method is used to return the current string of the CheckBox control itusacicuagea Wiese chee property is changed in the CheekBox control, the OnCheckedChanged [OnMouseUp It is used when it receives the OnMouseUp event in the CheckBox control CheekBox Events There are some Events of the VB.NET CheckBox control, Event Description IcheckedCuanged es GheckedChanaed event is found when the value of the checked property is changed to [DoubleClick [it oceurs 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 © scanned wth oxen Seamer Example: Code: Dima As String Button! Click() 404-.NET Programming Ifchke,Checked = True Then +chke.Text +"" re ee, End If language Ifchkeplus.Checked = True Then a=a+tchkeplus.Text+" " Boer End It OVBNET peomnecmee 2s Ifchkjava.Checked = True Then comma a+=chkjavaText +" " Python End If — os Ifchkvb. Checked = True Then a= chkyb.Text +" " Language End If You Kow C language C++ Java Ifchkpython.Checked = True Then 14= chkpython.Text +" " End If Labell Text = Labell.Text + MsgBox(a) End Sub Radio Button It is also known as an option button. We can Checked or Unchecked the radiobuitton We can take RadioButton on the form when multiple options are there and selection is only one. Like gender, stream, initial name, ete When the user checks one radio button within a group, the others get unchecked. RadioButton can make its own group when kept in container. To create multiple groups on one form, place each group in its own container, such as a GroupBox or Panel control Most useful property of the RadioButton is Checked - Defauit value is False, set it to True if you want the RadioButton to be displayed as checked. + The CheckChanged event is raised when the value of the Checked. ‘There are following properties of the VB.NET RadioButton control. Property Description [tis wed to set or get value representing whether the RadioButton allows the user to dragon the [ston Drop ed to set oF get a value representing whether the Radi 1 user to drag o form. [Appearance It is used to get or seta value that represents the appearance ofthe RadioButton. [AutoSerollOfiet| It is used to get or set the radio control in SeroliControllntoView(Contro) [The AutoCheck property is used to check whether the checked value or appearance of control can be [AutoCheck [automatically changed when the user clicked on the RadioB uton contol ini ‘The AutoSize property is used to check whether the radio control can be automatically resized by tobe jetting a value in the RadioButton control, [A CanSelect property is used to validate whether a radio control can be selected by setting a value in (CanSelect |e RadioButton contrat [checkatign _|t'8 sed 0 obtain or set value that indeates the Tosation ofthe check portion in the radoButton control [rext [The Text property is used to set the name of the RadioButton control. © scanned wth oxen Seamer 404- NET Programming. RadioButton Methods ‘Method Name Description [Contains(Control) | ‘The Contains) method is used to check ifthe defined control is available in the RadioButton [DefWndProc(Message)| It is used (o send the specified message to the Window procedure, [Destrottandieg tis used to destroy the handle associated with the RadioButton Control [Focus ‘The Focus() method is used to set the input focus to the window form's RadioButton control icetau izeMode() [ReserText), = 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 forr [AS the name suggests, a ResetText() method is used to reset the property of text t0 its default I is used to reroute an invalid field, which causes control in the elient region. RadioButton1.CheckedChanged() If RadioButton! Checked Then Label2.Text = RadioButtonl.Text End If cama RadioButton2.CheckedChanged ‘© General If RadioButton2.Checked Then © Special Label2.Text = RadioButton2.Text © Deux End If ete ose RadioButton3.CheckedChanged If RadioButton3.Checked Then Label2,Text = RadioButton3.Text End If Your Room ypeis: Delux Date Time Picker ‘It represents a Windows control that allows the user to scleet a date and a time and to display the date and time ‘with a specified format . It makes easy to work with dates and times because it handles a ot of the data validation automatically. Properties of the DateTimePicker Control ‘There are some properties of the VB.NET DateTimePicker control. Property Description [BackgroundImage |[t is used to set the background image for the DateTimePicker control [CalendarFont It is used to set the font style for the ealendar in the DateTimePicker control (CostomFormat [THe CustomFormat prope is sed ost te cstom date and time frat sing inthe [Controls [tis used to obtain the collection of controls that are stored within the DateTimePicker control eiiackad [A checked property is used to check whether the value property is checked with a valid date and ime in the DateTimePicker control Format [The Format property of the DateTimePicker is used to set the format for the Date and time \displayed in the Windows Form, — [The MaxDate property of the DateTimePicker is used to set the max data and time in control selected by the user. [Name [The Name property of the DateTimePicker control allows the user to set the name of the control [MinimumDateTime][t is used to set the minimum date value that can be allowed by control © scanned wth oxen Seamer 404-.NET Programming Methods of the DateTimePicker Control ‘There are some Methods of the VB.NET DateTimePicker control. Method Description [Contains(Controb) itis used to validate whether the specified control isa child of the DateTimePicker control or not It is used to force the creation of visible control to handle the ereation and any visible child controls, [The GetAutoSizeMode() method is used to check the behavior of the DateTimePicker control when the AutoAize property is enabled. [ResetBackColor() itis used to reset the back color ofthe DateTimePicker control. \createControl() |GetAutosizeModeo| [Select [The Select() method is used to start or activate the DateTimePicker control [Show() [The Show() method is used to display the control to the user. : Fhe ToString) method is used tortura sting that represents he curteat DateTimePieker [Tostringo) Pe ial eeeen fence Dima, b As DateTime Dime, d As TimeSpan Button1.Click() Saver BmOae: [iF Ast 182 a= DateTimePickerl. Value b=DateNow =] = bSubtraci(a) Label3. Text = Val(c-TotalDays) / 365, ee List Box A ListBox control displays a list of items from which the user can select one oF more. List boxes are best used for displaying large number of choices, * CheckBox control occupies space in the form. For example, If we give 50 ct checkboxes for it then our form will be filled with checkboxes only moreover, it occupies more space. Instead we give 50 choices in the ListBox then it will look better and neat ‘A scroll bar automatically appears when many items in the ListBox. ‘By default we can select only single item from the ListBox. ListBox Properties 1s to the user and if we use Properties Name [AllowSelection || takes a value that defines whether the list box allows the user to select the item from the I [ColumnWidth |i is used to get or set the width of the columns in a multicolumn Listbox. Description [Container __||As the name defines, a container gets the [Container that stores the component of ListBox control [Controls [tis used to get the collection of controls contained within the control [Created It takes a value that determines whether the control is created or not. [Width It is used to set the width of the ListBox control. vissite It takes a value that determines whether the ListBox control and all its child are displayed on the |Windows Form, [SelectionMode _|I is used to get or set the method that determines which items are selected in the ListBox. [MultiColumn _ [It allows multiple columns of the item to be displayed by setting the True value in the Listbox. [items [it allows the collection of items in listbox ListBox Methods Method Name Description [aaa [The Adal) method is used to add items to an item collection. lRemove() tis used to remove an item from an item collection, We ean remove items using the item name. © scanned wth oxen Seamer 404-.NET Programming [ctearo is used to remove all items from the item collection atthe same time. [Contains() I is used to check whether the particular item exists in the ListBox or not. [showo I is used to display the control to the user. [Sort [AS the name suggests, a Sort() method is used to arrange or sort the elements in the ListBox. [ReserText) _|A ResetText() method is used to reset ListBon’s text property and set the default value. [ResetBackColor()|It is used to reset the backColor property of the ListBox and set the default value. Example Add_Button.Click) ListBox! Items. Add(TextBox!.Text) Label3.Text = ListBox Items,Count() TexiBoxl.Text =" TextBosl.Focus() Remove_Button.Click0) ListBox! Items, RemoveAt(ListBox! Selectedindex()) Label3.TText = ListBox ltems,Count() Clear Button Click) ListBox! .tems.Clear() Label3 Text = ListBox. Items.Count() ‘Combo box = ComboBox is a combination of a TextBox and a ListBox. The ComboBox displays an editing field (TextBox) combined with a ListBox allowing us to select from the list ‘orto enter new text. ‘+ Runtime user can enter new data to the combo box control but new data store in it temporary. ‘= User can select only one item from the given list, ‘= It takes little space on the form and store long selection data + By default, the ComboBox control appears in two parts: Top part + List part © The top partis a text box that allows the user to type a lst item. ‘= The list part displays a list of items from which the user can select one. + For example use ComboBox for list of Cities, list of Countries, ete. The text portion is editable, The list portion is always visible. = Wecan add items, remove items and check items, ete are same as ListBox control Description ‘The AllowSclection property takes the value that indicates whether the list allows selecting the hist item, [AutoCompleteMode || It takes a value that represents how automatic completion work for the ComboBox [Created Takes a value that determines whether the contol is ereated oF not. [DataBinding lis used to bind the data with a ComboBox Control. [BackColor The BackColor property is used to set the background color of the combo box control [DataSource Iris used to get or et the data source for a ComboBox Control. Fiaestyle Iris used to set the style or appearance for the ComboBox Control ‘The MaxDropDownltems property is used in the combo box control to display the maximum [MaxDropDownltems! umber of items by setting a value. [MaxLengeh Its used by the user to enter maximum characters inthe 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. © scanned wth oxen Seamer 404-.NET Programming + ComboBox Events Events Description lFontChangea Teoceurs when the property of the font value is changed. [Format ‘When the data is bound with a combo box control, a format event is called, [SelectindexChanged] It occurs when the property value of SelectindexChanged is changed. [HelpRequested ‘When the user requests for help in control, the HelpRequested event is called. [Leave occurs when the user leaves the Focus on the ComboBox Control. Example Button?,Click ComboBox Items. Add(TextBox! Text) ComboBox1.SelectedIndexChanged Label3,Text = ComboBox..Selectedltem() Picture Box = Picture Box control is used to display the images on Windows Form. © The Picture Box control has an image property that allows the user to set the image at runtime or design time. icture Box Properties of the There are following properties of the VB.NET Picture Box control, Property Description [BackCotor [It is used to set the background color for the Picture Box in the window form. Pickgrsuaalaange ie ‘used to set the background image of a window form by setting or getting value in the picture a |The Errorlmage property is used to display an image if an error occurs while loading an image on a ree See {window form. aiid [The initial image is used to display an image on the Picture Box when the main image is loaded ana fonto a window form by setting a value in the Picture Box control, [SizeMode_ [It represents how the Picture Box will handle image placement and control sizing [Text [It is used to set text for the picture box controls in the window form. [image [The image property is used to display the image on the Picture Box of a Windows form. [Borderstyle lit is used to set the border style for the picture box in the windows form. imageLocation I. famed ‘to set or get the path or URL of the image displayed on the picture box of the window 8 of the PictureBox Control ‘There are some Events of the VB.NET PictureBox control. Events Description [BackColorChanged It occurs when the property of the backcolor is changed in the PictureBox control. it occurs when the property value of the Backgroundimage is changed in the [PictureBox control, It occurs when the property of the ContextMenu is changed in the PictureBox. {contro [BackgroundImageL ayoutChanged |CcontextMenuChanged [Resize [The resize event occurs when the picture box control is changed. © scanned wth oxen Seamer 404-.NET Programming Example: — PictureBox Form_Load() Me.Text = "PictureBox Example" "Set the ttle name for the form Button! Text = "Click to display the imay Button}. ForeColor = Color-Green Buttonl_Clickg) PictureBox! mage = Image.FromFile("F:\VBLOGO png") "PictureBox!_SizeMode ~ PictureBoxSizeMode Stretchlmage PictureBox! Height = 250 PictureBox! Width = 400 Button1. Visible = False Rich Text Box + Its an advance version of TextBox. + Difference between TextBox and RichTextBox is ike Notepad and WordPad, + It provides more advanced text formatting option + Itcan load RTE,TXT format files for reading or editing. + The wordpad save i's file in RTF format. The fall form of RTF is Rich Text Format. + RichiTextBox allows formating the text, say adding colors, displaying particular font types, selected text effect, bullets, alignment, indents and so on. + By default RichTextBox is multiline, By default maxlength of it 2147483647, + Some properties of RichTextBox are BulletIndent, Selection Font, Selection Color, Alignment, ee + _ Best example of RichTextBox is WordPad. Properties: Properties [Description lasaiota Peper ator ste vale apecijing fo change ther et Ga aston te font BackColor [Property used to Get or set background color for the control [AutoWordSelection [Property used to set or get a value specifying automatic word selection ‘anRedo [Property to used to indicate that any actions can be reapplied. anlUndo [Property to used to undo any previous actions. [HideSetection [Property used to set or get value specify a text should stay highlighted when control loses focus, iaxLength [Property used to set or get the maximum number ofa line a user can type into a rich text box. lultiine [Property used to set or get a value specifying multiline input for the control SerollBars [Property used to set or get the kind of seroll bar to be used. electedText [Property used to set or got the selected text within the control ‘lectionColor __ [Property used to set or get color forthe selected text Property used to set or get the number of characters selected in the control, [Property used to set or get the font for the selected text, [Property used to set or got the current text in the control © scanned wth oxen Seamer 404-.NET Programming Methods: ethod Description [Appends “Method used to append text to current text ofthe control anPaste “Method determines if the infromation can be pasted froma clipboard “Method used to clear text from the control “Method used to search a text inside the control ‘Method used to get the line number from the specified character position GetPositionFromCharindex| Method used to get the location within the control at the specified character index. [LoadFile “Methods used to load the contents ofa file into the control Redo “Method to reapply the last operation, elect “Methods used to select the text within the control indo ‘Method to undo the last edit operation, Description Triggered when the control is clicked. [LinkClicked Triggered when the user clicks on the link within the text (odifiedChanged Triggered when the value of the Modified property is changed. eadOnlyChanged Triggered when the value of the ReadOnly property is changed. electionChanged Triggered when the value of the Selection property is changed. VSeroll Triggered when the vertical scroll bars are clicked. Example: Bag) ee Bis is cornet PEE }E8 Sete fF Pen HS Code: Dima, b As Integer Dim str As String Button Click) a= Val(TextBox! Text) b= Val(TextBox2-Text) Fori=1To 10 Forj=aTob RichTextox Append Text(String Format("{0) * {1) = (2}",j.i, Gi) ToString().PadRighn(10))) Next RichTextBox1.AppendText(vbCrLD), Next © scanned wth oxen Seamer 404-.NET Programming Tree View The TreeView control is used to display a hierarchical representation of the same data in a tree structure, ‘© Windows Explorer and Solution Explorer contain Tree View control + TreeView control is collection of nodes. The main starting node is called root node. Under the root, areal te is made of branches and leaves. * Anode can havea node as a child Ween expand and collapse these nodes by clicking on the plus sign (+) button, = Wecan display TreeView control with check boxes next to the nodes, if the TreeView’s CheckBoxes. property is set to tue. [tis also useful to provide the full path of the root node to the child node. Properties of the TreeView Control There are following properties of the TreeView control. Properties Deseription [Nodes [The nodes property ofthe tree view control is used to gather all the nodes used in the tree. [SelectedNode __|Itis used to obtain or set the tree node that is selected in the tree view control. It gets or sets a value that represents whether you want to draw lines between the tree nodes connected] th the root of the tre view. |showRootLines [The Path Separator property of the Tree View Control is used to set a delimiter string between the tee| [path Separator ro. paths It is used to get or set a value representing whether you want to display the plus (+) or minus sign utton next to tree nodes containing the child nodes. It takes a value representing whether you want to draw lines between the tree nodes of the tree view ontrol IW is used to gat or set full visible tree nodes on top of other nodes in the Wee view control It's used to obtain the fully visible tree node in the tree view control [The ItemHeight property is used to set the height of each tree node in control [The Scrollable property is used in the tree-view to display the scroll bar by setting the value in sontro, |showPlusMinus IShowLines [Serollable Methods of the TreeView Control Method. Description [GetNodeAt [A GetNodeAt() method is used to get a node atthe specified locaton of the tree view control sort, [A Sort method is used to sort the tree nodes that are available inthe tree view control [ExpandAN [As the name suggests, an ExpandAll method is used to expand all the tree nodes [GetNodeCount [It is used to count the number of nodes that are available in the ree view control [ColapseAll [it is used to collapse all tee nodes. including all child nodes inthe tree view control ‘Example: 7 - 7 = Load() TreeView2.Nodes.Add( "Computer" TreeView2.Nodes(0).Nodes.Add("Hardware") TreeView2. Nodes(0).Nodes(0).Nodes. Add "Mouse") TreeView2.Nodes(0).Nodes(0) Nodes. Add "Keyboar TreeView2 Nodes(0).Nodes(0) Nodes. Add(" Monitor") TreeView2.Nodes(0).Nodes(0).Nodes.Add("Speaker") ) ‘TreeView2.Nodes(0).Nodes. Add("'Software") TreeView2.Nodes(0).Nodes(1).Nodes.Add("Word") TreeView2.Nodes(0).Nodes( 1). Nodes. Add("Excel”) TreeView2.Nodes(0).Nodes( 1). Nodes. Adal "PowerPoint") ‘Tree View2.Nodes(0).Nodes(1).Nodes. dl "Internet Explorer") © scanned wth oxen Seamer * ‘TreeView2.Nodes(0).Nodes.Add(""Firmware") TreeView2.Nodes(0).Nodes(2).Nodes. Add Microwave Oven! TreeView2 Nodes(0).Nodes(2).Nodes.Addt"Washing Machine") TreeView2.Nodes(0).Nodes(2)-Nodes.Add("Retrigrator") TreeView2,Nodes(0).Nodes(2).Nodes.Addt"Television") Tool Tip + Turepresents a small rectangular pop-up window that displays a brief description of control * It is used to provide hints to a user when the user places the pointer on a control. + is typically wed to alert users tothe intended use of a contol Properties: Properties Description BBackColor Property wed to Gel oF se background color Tor the control [NutomaticDelay | Property used to set or get the automatic delay for the tool tip. [NutoPopUpDelay] Properly used to seta delay Tor automatic pop up of the control initalDelay Property ised to set an initial dolay Tor the contro [TootTiptoon Property used to choose the Iype of tooltip eon BhowAtwa Properly used fo get oF set whether the tool lip should be appear when is parent conivols inactive Events [Events [Description GelTooiTip [Returns a tool tip text et ToolTip _[Connees tooltip text with the fool Up, Example: ‘TextBoxl_Mouseltover Q) ‘ToolTip1.SetToolTip( TextBox, "Enter Your Full Name") Button_click() MsgBox("Hello " & TextBox!.Text) Progress Bar + The Window Progress Bar control is used by the user to acknowledge the progress status of some defined tasks, such as downloading a large file from the web, copying files, installing software, calculating complex results, and more Properties of the ProgressBar Con There are following properties of the VB.NET ProgressBar control. Property Description [MarqueeAnimationSpeed| It is used to determine the progress status for a progress bar in milliseconds, ‘The padding property is used to create a space between the edges of the progress bar by esas setting the value in the progress bar contro step Iris used to get or seta value in control that ealls the PerformStep method to inerease the current state of the progress bar by adding a defined step [Maximum is used 10 set the maximum length of the progress bar contro inthe windows form, [Minimum Tis sed 10 set oF get the minimum value ofthe progress bar control in the windows form isin I obtains a value representing whether the progress bar control enables the user to be dragged onto the form. Its used to seta value that represents how types the progress bar should be displayed on the Windows Form, © scanned wth oxen Seamer 404-.NET Programming Methods of the ProgressBar Contr Event Description [ForeColor | _ The ForeColor method is usd to reset the forecolor tots default valu [PoString |The Tostring method is used to display the progress har contol by seturing the tring. increment | _It is wed o increase the curent state ofthe progress bar contol by defining the specified time, PerformStep [__Itis wed to increase the progress barby sting the step specified in the ProgressBar property Events of the ProgressBar Control Events Description [Ceave The Leave event occurs when the focus leaves the progress bar como [MouseCtick [A MouseClick evem oceured when the wer clicked on the progress bar confol bythe mouse FexiChanged | oceus when the property ofthe wext is changed in the progress bar contol [PadaingChangedt occurs when the paling propery is changed in the progress bar contol Example: Start_Button.Click() ‘Timerl.Enabled = True ProgressBar]. Maximum = 100 ant Reset_Button.Click() a=t ProgressBarl.Value= 0 Labell Tex Timerl_Tick) : ProgréssBarl. Value ~ ProgressBarl. Value +1 Label Text = "Process" & a & *% Completed” Ormn atl Ita> 100 Then Timer] Enabled = False End If Masked Text box = The NET MaskedTextBox control provides a mechanism to validate user input on @ Form, = For example, if you need a TextBox that should accept dates in a certain format, you should set the masking in the MaskedTextBox. + The MaskedTextBox uses the Masked TextProvider mask syntax. = The mask is used to distinguish between proper and improper user input. Properties: Properties Description [TextAlign ‘Text alignment is set using this property. ask This property is used to set the predefined mask description [HidePromptOnLeave | Property used to hide the mask characters, literals when the focus is Tost from the control [AllowPromptAstnput___| Property used to set the input character as per the specified by moving character. [TextiMaskF ormat Property used to specify the formatting for the text fejcatnpuOnFinaraitr] Pope we a ose 8 ‘Value indicating whether to stop user input after the fist © scanned wth oxen Seamer 404- NET Programming * Notify Icon + It specifies a component that ereates an icon in the notification area. + Icons in the notification area are shortcuts of an application that are running in the background of computer, such as a virus protection program or a volume control These processes do not come with their own user interfaces. Properties: [Properties Des ontextMenur | Property gts or ses the content menu Tor the Way Toon eon Property used to Get or sets the current icon. [Tew Property used to Get or set the toolip text when mouse hovers the icon sible Property 10 used 10 make the icon visible or invisible Methods ethod Deseription Dispose ‘Method used 0 release all the resouraes used By the component Finalize Method used to release all unmanaged resources. do cleanup operation before garbage collection GeiServiee “Method used 10 retum the object that represents the service provided by that component SetT ype Method used to get the type of current Instance. howBalloonTips | Method used to display a balloon tip for the specified time period Events: Events [Description Tick [Triggered when the icon the inthe system way is clicked, DoubleClick Triggered when the icon the inthe system tay is double clicked. jouseDown flriggered when the wer presses the mouse buton on the icon jouseMove [Triggered when the user moves the mouse over the icon. fouseUp [Triggered when the user releases the mouse button on the Toon Example > Place one button and Notifyleon in the form as follow: > Set Ieon property of Notifylcon control and change Text property of Button control, After Click on Button at Runtime see at Notification Panel aI Notiyicont After Click on Icon from Notification Panel: Button!_ClickQ) Me Hide) Noiifjteon_APP.ShowBalloonTip(30, "CLICK ME Tam here in Notification Pane, Click me..", Too! Tipleonnfo) Notifyleon_APP_MouseClick() MeShow() Notifylcon_APP.ShowBalloonTip(30, "CLICK ME", "Hello... lam Back", ToolTiplcon.Info) © scanned wth oxen Seamer ° 404-.NET Programming Link Label + Itissimiar to a Label control, but it ean display a hyperlink ‘+ Multiple hyperlinks can be specified in the text ofthe control + Each hypertink ean perform a different task within an application. ‘+ Each hypertink displayed in the LinkLabel control is an instance of the LinkLabel.Link class. +The LinkLabel.Link class defines display information, state, and location ofthe hyperlink. Prope [Properties [Description [TestAlign [Text alignment is set using this property either t right or left by giving values O or 1 [Text roperty wed for the label text eight [This propery is used to specify height ofthe control. Yih [This propery is used to specify the width ofthe control [Backsivle [Property used to make a label wansparent oF opaque. [Autosize Property is used o adjust the label text horizontally YordWrap Property is used to adjust the label vertically [NetivelinkColor [Property wed to specify the color ofthe active link [DisabledLinkColor [Property used to specify the color ofthe disabled link. inkColor [Property is used to specify the color for a normal link, fsitedLinkColor [Property is used to specify the color fora visited link. Events: [events Description inkClicked_ [Triggered when the link is clicked, Example: Buttont_ClickQ Process. Star(" www: google.com") LinkLabell_LinkClicked() Process. Star("www-google.com") LinkLabel2.LinkClicked() Calculator. Show LinkLabelS.LinkClicked)) checkbox. ex.$how() LinkLabeld.LinkClicked) Listbox ex! Show() LinkLabel3.LinkClickedO Tie Tac Toe Game,Show0 © scanned wth oxen Seamer 404- NET Programming © Checked List box ‘The CheekedListBox is similar to Listbox except that it displays al items in the list with a cheekbox that allows users to check or uncheck single or multiple items. CheckedListBox Properties Properties Description ara it obtains a value that determines whether the AccessibilityObject is assigned to the [AecessibilityObject |Cecked istBox control |AccessibleName it gets or sets a value that tells ifthe accessible client application has used the name of the |checkedtistbox control [AllowSelection [It gets a value that indicates whether the ListBox allows forthe item to be selected from the list. It wets or sets a value representing whether the CheckedListBox control is scrolled in [MowSeollOnset | serotiControlinio View Contro) [BorderStyle Iv is used to set the type of border around the Checked istBox by getting or siting a value [Checkedttems [iis used to store a collection of checked items in the CheckedListBox. It is used to set or get a value that indicates if the vertical scroll bar appears in Windows Forms at all times. [Setecteditems Iv is used to get all selected items from CheckedListBox. SelectlonMode ts used to get or sta value representing the ems’ selection mode inthe Checked iBon [FopIndex lcs used to set the first visible tem atthe top of the index inthe CheckedLisBox, CheckedListBox Methods “Methods Description [ClearSetectd fis wed to uselewall the selovted ems in the CheekedLfiBox [CreateaccessibiliyInstanceO jis ued to create new accessbiliy ofthe object inthe Checked. inBox Comrol |CreateltemCollection() lit is used to create a new instance for the collected item in the list box. [DestroyHandle() IIt is used to destroy the handle associated with CheckedListBox. |It is used to validate whether the specified object is equal to the current object in the [Equals(Object) |CheckedListBox or not. 2 : 2 — [FindForm() lIt is used to obtain the form in which CheckedListBox has control. |GetltemText(Object) It is used to get the text of the specified item in the CheckedListBox. [GetType) Ics used o get the curentiem type in the CheckedLstBox. howd [A Show) method is wsedto display the CheckedLtBox Conta ote we. sor [A Sort) method is used 0 sont or organize al the ems available in Checked istBox Example: Add_Button_ClickQ, ‘CheckedListBoxl Items.Add(TextBoxl Text) Label3.Text Remove Button Click( Dim a = (From i In CheckedL istBox! Checkedltems) ToList For Each i Ina * MsgBoxti) CheckedListBor Next Label3.Text = CheckedListBox!_Items.Count() Clear Button Click) CheckedListBox CCheckedl.istBox!. Items. Count() ee (owteiaat | nItem Remove(i ToString) | Items.ClearQ) Label3.TText = Checked istBoxl.Items.Count() © scanned wth oxen Seamer 3.1.2. Conti er Controls 7 Containers Container controls, as their name implies, are controls that can host other | & Pointer controls inside them. The Form is the perfect example here, as you put all your | = Foy.syoutPanel controls on the form. The host is known as the parent, and the controls inside the outs host are known as the children. Container controls can obviously host other eae Container controls as well; then you're looking at a grandparent, parent and child Panel relationship. SplitContainer TabControl (1) GroupBox TableLayoutPane! = A GroupBox control is a container control that is used to place Windows Forms child controls in a group. = The purpose of a GroupBex is to def user interfaces where we can categories related controls in a group, Property: Text: It is used to speity the caption to be displayed for Groupbox contro. Event: Enter: Occurs when the mouse is entered. Methods: (OnEnter: It raise Enter event, (2) Panel It is used to group collections of controls. As GroupBox, itis a container for other objects As with other container controls, ifenabled property of the Panel control is set to false, the controls contained within the Pane! will also be disabled ‘The Panel control is displayed by default without any borders, It-does not have caption. Panel Control Properties Property Description BorderStyle | It indicates the border style for the control Enabled It gets or sets value indicating whether the control can respond to user interaction. HorizontalScroll |"It gets the characteristics associated with the horizontal serol bar, HScroll It gets or sets a value indicating whether the horizontal scroll bar is visible. VerticalScroll | It gets the characteristics associated with the vertical seroll bar. VSeroll It gets or sets a value indicating whether the vertical scroll bar is visible. aint, Default Event Example: Personal Information © scanned wth oxen Seamer 404-.NET Programming (3) TabControl Tt contains tab pages, which are represented by TabPage objects. ‘The order of tab pages in this collection reflects the order of the tabs appear in the control. ‘The user can change the current TabPage by clicking one of the tabs in the control = It manages a related set of tab pages. TabControl Properties Property Description Alignment Tt gets or sets the area of the control where the tabs are aligned. [Appearance __| It geis or sets the visual appearance of selected tab of the control mage List Tt gets or sets the images to display on the tabs, TtemSize I gets or sets the size of the tabs, MultiLine It gets or sets a value indicating whether more than one row oF tabs can be displayed. RowCount | Itgeis the number of rows that are currently being displayed in the selected tab of the contro. SSelectedindex | It gets or sets the index of the currently sclected tab page. SelectedTab | Tt gets or sets the currently selected tab page. ‘Show ToolTips | It gets or sets a value indicating whether a tab’s ToolTip is shown when the mouse passes over the tab. TabCount gets the number of labs in the tab strip. TabPages It gets the collection of tab pages in tab control TabControl Methods Method Description Deselect Tab Ttunselects the tab of the control Remove All Teremoves all the tab pages and additional controls from this tab control. SelectTab It makes the tab with the specified index as current tab. ¥ Default Event: Click) TabPage object Itrepresents single tab page of the TabControl TabPage Properi Property Description Image Index It gets or sets the index to the image displayed on tab. Text Tt gets or sets the text to display on the tab. ToolipTeat | It gets or sets the ToolTip text for this tab, Example: Lode Regtiten sents Conte © scanned wth oxen Seamer 404- NET Programming ore (4) SplitContainer ‘+ Itrepresents a control consisting of a movable bar that divides a display area of a container into two resizable panels. You can add controls to the two resizable panels, and you can add other SplitContainer controls to existing SplitContainer panels to create many resizable display areas. + When the user passes the mouse pointer over the spliter, the cursor changes, which indicates that the controls inside the SplitContainer control can be resized. SplitContainer Properties Property Deseription ‘Active Control It gets or sets the active control on the container control. Orientation It gets or sets a value indicating the hotizontal or vertical orientation of the SplitContainer panels Panell Ii gets the let or top panel ofthe Split Container, depending on Orientation. Panell Collapsed — | It gets or sets a value determining whether Panell is collapsed or expanded. Panel Min Size It gets or Sets the minimumn distance in pixels of the splitter from the right or bottom edge of Panell Pancl2 [i gets the right or botiom panel of the SplitContainer, depending on Orientation Panel2Collapsed | It gets or sets a value determining whether Panel2 is collapsed_or expanded. Panel2MinSize It gets or sets the minimumn distance in pixels of the splitter from the right or bottom edge of Panel2 SpliterDistance Ii gets sets the location of the splitter, in pixels, from the left or top edge of the SplitContainer. Splitterinerement | It gets or sets a value representing the increment of splitter movement in pixels. Splitter Width It gets or sets the width of the splitter in pixels ¥ Default Event: Paint() Example Orientation: Vertical Orientation:Horizontal © scanned wih oFEn Seamer PR | (5) FlowLayout Panel + Itrepresents a panel that dynamically lays out its contents horizontally or vertically. + Tis contents can be wrapped from one row to the next or from one column to the next + Alternatively, its contents can be clipped instead of wrapped, FlowLayout Panel Properties Property Deseription DefaultPadding It gets the internal spacing. in pixels. of the contents of a control FlowDirection Tt gets or sets a value indicating the flow direction of the FlowLayout Panel control Margin Tt gets or sets the space between controls Padding It gets or sets padding within the control RightToLeft It gets or sets a value indicating whether control's elements are aligned to support locals using right-to-left fonts ‘WrapContents Tt gets or sets a value indicating whether the control should wrap its contents or let the contents be clipped. v Default Event: Paint Example: 's| Jo) || ||) [> (©) TableLayout Panel + Ibrepresents a panel that dynamically lays out its contents in a grid composed of and columns * Margin, DefaultPadding, Padding properties of TableLayoutPanel is similar to FlowLayoutPane! Control ‘TableLayout Panel Properties Property Description Cell BorderSiyle It-gets or sets the style ofthe eell borders ColumnCount It gets or sets the number of columns in the table, ColumnStyles It gets a collection of column styles for the Table LayoutPanel RowCount It gets or sets the number of rows in the table. Row Styles| Tt gets a collection of row styles for the TableLayout Panel © scanned wth oxen Seamer 404- NET Programming TableLayout Panel Methods Method Deseription (GeiCellPosion Ie gets Cell Poon ofthe TabicLayout Panel that ropaesens the row and the column ofthe eel aC 1 eu te Slum poston OF he speed sil com GeiColumnSpan Feu the munber oF eolums spanned bythe speed cit Gone (GeiColurmWidlisIereturs an array representing the widths in pines, ofthe columns in the Tabicayout Panel GasRow Te returns the ow positon oF the spesifed ei contol GesRowSpan Trams the numberof tows spanned by te specified child contol CGeiRow Heights Tr rturs an array representing the heights, in pixel, of the rows in the TabeLayouPandl SeCellPosiion —Itsets Cel Position ofthe TaleLayoutPane ht represen the ow andthe column ofthe el SeiColumnSpant Trelis the numberof columns spaned by the cild contol SeCalnn Tests the coli position ofthe speed hid contol SetRow Itsets the row position of the specified child control. SaiRowSpan Tess the numberof os spanned by the eid contol Example eT 3.1.4 Component Controls (1) Image list (2) Error provider (3) Help provider (4) Timer (1) Image List + Tris used to store images * Itisone kind of image repository. + Controls having Imagelist and Imagelndex properties uses Imagelst contro. * Such controls are list view, tree view, toolbar, tab control, checkboxes, buttons, radio buttons and labels. Properties: Properties Description ColorDepth Property gets the color depth for this image list. Tmages Property gets an ImageC ollection object for this image Tist ImageSize Property used to-get or set the image size forthe images in thelist ‘TranspareniGolor Property used to-get orset the transparent color for ths list Methods: Method Deseription Draw ‘Method used 19 draw the given image. © scanned wth oxen Seamer 404-.NET Programming (2) Timer ‘+ ‘The timer control isa looping control used to repeat any task ina given time interval ‘+ Itisan important control used in Client-side and Server-side programming ‘+ Furthermore if we want to execute an application afier a specific amount of time, we can wse the Timer Control. + Once the timer is enabled, it generates a tick event handler to perform any defined task in its time interval property. ‘+ It starts when the star() method of timer control is called, and it repeats the defined task continuously Until the timer stops. Properties: Properties Deseription Name__ |The Name property is used to set the name of the control Enabled _| The Enables property is used to enable or disable the timer control. By default, itis True. ‘An Interval property is used to set or obtain the iteration interval in milliseconds to raise the timer jcontrol's elapsed event. According to the interval, a timer repeats the task, Interval Events of Timer Control [Ever Description [A tick event is used to repeat the task according to the time set in the Interval property. Itis the default event of [Tick la timer control that repeats the task between the Start() and Stop) methods. Methods Methods. Description 7 ‘The Stari() method is used to begin the Timer control's elapsed event by setting the ‘0 [Enabled property to true. to ‘The Stop0 method is used to siop the timer controls elapsed event by setting Enabled PO property o false Example: > Set Images and ImageSize property of Imagelist Control. Dim n As Integer =0 Start Button.Click Timerl Star) Timerl Interval = $00 Stop Button.Clicki Timerl.Stop)) Image Slide Show Using ImageList ‘Timer Tick: PictureBoxI Image = Image ist Images(n) If n=ImageListl-Images.Count() - 1 Then n=0 Else ntl EndIf Prmageis — OTe © scanned wth oxen Seamer 404-.NET Programming (3) Error provider * ErrorProvider allows us to set an eror message for any control on the form when the input is not valid When an error message is set, an icon indicating the error will appear next tothe contol andthe error message is displayed as Tool Tip when the mouse is over the control. Properties Properties Description Teon __|Gets or sets the Teon that is displayed next to a control when an error occurred. BlinkRate|which allows setting the rate in milliseconds at which the icon blinks, BBlinkStyle|Gets or sets a value indicating when the error icon flashes Methods: Methods Description [cettconatignment | 2% value indicating where the eror icon should be placed in relation tothe control, \SetleonAlignment |i £258 value indicating where the error icon should be placed in relation tothe control. ‘SetError It sets the error description string for the specified control (Geté:rror It retums the current error description string for the specified control Exampl Mebile Ne: [S| ace EaD tel |} ErrorProvidert Cheek Cheek_Button() IENot IsNumeric(TextBox1 Text) Or Not TextBoxt-Text Length = 10 Then EnrorProvider| SetFrror(TextBox!, "Please Enter Only 10 Digit number") Else ErrorProvider|SetError(TextBox!, ") MsgBox(TextBox!.Text) EndIf (4) Help provider + This control provides pop-up or on line help for controls + HelpProvider control Provides help with your applicati more easily. + Support for help in Visual Basic exists and you can display HTML files that ean contain a set of linked topics + Help class: * The Help class allows us to display HTML help to users. * The Help class provides two methods: Showielp and ShowHelplndex. ShowHlelp - ShowHlelp is used to display a help file for a particular control and requires that control to be displayed along with the help file, The URL you specify for the help file can be in the form of F:\myHelp (local machine) or http\www.vbheaven.com|help-him (Web). ShowHelpindex -Show!clpIndex method is used to display the index of a specified help file. You call the ShowHelpIndex method just like you call the ShowHelp method is very useful as it allows your users to understand it © scanned wth oxen Seamer 404- .NET Programming ‘© HelpProvider Component: ‘+ The HelpProvider component provides these additional properties to each control on the form. These properties are: HelpString - Determines the help string associated with a control ‘ShawHelp - Determines if help should be displayed for this control + Using the property display a help on the button when we press Fl. * Firstly set ShowFielp property of the The HelpProvider component(Button) True * The following code displays a help string when Button? has the focus and F1 key is pressed. Form1_Loado eipProvidertSetHelpString(ButtonL., "Please Help me") Buttont_Click) Help ShowHelp(Button1,"F:/helpfile.html") 3.2. Working with Menus and Dialogue Boxes ++ Menus & Toolbars a “2 Menus & Toolbars Pointer ContertMenustrip MenuStrip StatusStrip Too'stipContainer (1) Menus 5B Menuseript ‘A menu is used as a menu bar in the Windows form that contains a list of related commands, and itis plemented through MenuStrip Control ‘The Menu control is also known as the VB.NET MenuStrip Control It provide a quick and easy way to add menus, menu items and submenu items to your application. It also provides a built-in editor that allows you to add, edit and delete menu items. ‘The menus can contains aceess keys, shorteut keys, check marks or radio buttons. Access Key: An access key also known as accelerator key allows users to navigate the menus using the Alt key anda letter that is underlined in the menu item. Shorteut key: shortcut keys allow you to invoke the menu item without displaying the menus at all, (Check marks and radiocheeks: Fither a checkmark symbol next to the menu item, or in the case of a radiocheck, a large dot next to the menu item. Both of these marks are indicators that the menu item is active. © scanned wth oxen Seamer 404- NET Programming Properties of the MenuStrip Control [Property Descript ‘Allow ItemReonder It gets or sets a value indicating whether drag and drop item reordering are handled, [Allow Merge Ti gets or sets a valuc indicating whether multiple MenuStrip can be combined. DDisplay Ttems It gets the subset of items that are currently selected. [Enabled Ti gels or seis a value indicating whether the control can respond to user interaction. limageList It gets or sets the image list that contains the image to be displayed Items Ti gets all the items, [Orientation It gets the orientation of the ToolStripPanel [Showltem TooITips It gets or sets a value indicating whether ToolTips are shown for the MenuStrip ‘Stretch It ges or sets a value indicating whether the MenuStrip stretches from end to end in its container. Text Ti gets or sets the tent associated with this control. ‘TextDirection Tt gets or sets the direction in which to draw text on a ToolStrip. Methods of the MenuStrip Control Method Description GeiNextliem Ttreirieves the next Item from the specified reference point and moving in the specified direction, ‘SeiDisplayed Items It resets the collection of displayed and overflow items after a layout is done. SetltemLocation It anchors an Item to particular place Eyents of the MenuStri Events Description [MenuActivate_ [When a user uses a menu bar control with a mouse or keyboard, a MenuActivate event occurs. /MenuDeactivate| The MenuDeactivate event occurs when the MenuStrip control is deactivated in the Windows form. Default Ever Click) Menultem ‘+ Itrepresents an individual item that is displayed within a MainMenu or ContextMenu. + ILis retained for both backward compatibility and future use. Property Description BarBreak It gets or sets a value indicating whether the Menultem is placed on a new line or in a new column, Checked It gets or seis a value indicating whether a check mark appears next to the text oF the menu item. Defaultitem It gets or sets a value indicating whether the menu item is the default menu item. IsParent It gets a value indicating whether the menu item contains child menu items. MenulD It gets a value indicating the Windows identifier for this menu item. Menuliems It gets a value indicating the collection of Menultem objects associated with the menu, MergeOrder It gets or seis a valve indicating the relative position of the menu item when itis merged with another. Merge Type ___ It gets or sets a value indicating the behavior of this menu item when its menu is merged with another. ShortCut It gets or sets a value indicating the shortcut key associated with the menu item. ‘ShowShortCut _ It gets or sets a value indicating whether the shortcut key that is associated with the menu item is displayed next to the menu item caption. Text It gets or sets a value indicating the caption of the menu item. © scanned wth oxen Seamer 404- NET Programming Methods: Method Description FindMenultem It gets the Menaliom that contains the value specified. FindMergePosition It returns the position at which a menu item should be inserted into the menu. GetContextMenu__It gets the ContextMana that contains this menu GetMainMenu It gets the MainMenu that contains this menu Marge Menu It merges this Menultem with another Menuliem and returns the resulting merged Menultem. Events: Event Description Perform(l Ttraises the Click event for menu item. PerformSclect raises the Select event for menu item. 2) ContextMenuStrip = Ttrepresents a shortcut menu, Context menu is @ menu popup over controls usually when user right clicks on them, They are called context ‘menus because they appear over specific controls, + Allowitem Reorder, AllowMerge, ImageList, Items, MaxltemSize, Orientation, + OverflowButton, ShowltemTooITips, Stretch, Text, and TextDirection properties are similar to MenuStrip contol ContextMenuStip cut 7 co = if FE ContextSdenuStript pote =|] sone Formate Alignment Properties of the ContextMenuStrip Control Property Description Allow Transparency It gets or sets a value indicating whether the Opacity of the form can be adjusted ‘AutoClose It gets or sets a value indicating whether the Drop Down contro! should automatically close when it has lost activation Opacity Ii determines the opacity of the form Ownerltem [It gets or sets the Item that is the owner of this DropDown. SoureeControl It gets the last control that caused this ContexMenuStrip to be displayed. TopMost, [i gets or sets a value indicating whether the form should be displayed as a topmost form, ‘ShowCheckMargin It gets or sets a value indicating whether space for a check mark is shown on the left edge of the Menu Item ‘ShowimageMargin It gets or sets a value indicating whether space for an image is shown on the left edge of the Menultem. It supports all methods of MenuStrip control below table represents the methods and its meaning, Methods Method Description Close Teloses the Control Show It displays the control on its default position, © scanned wth oxen Seamer 404- NET Programming. @) ToolStrip + Ieprovides container for Windows toolbar objects + ToolStrip is the base class for MenuStrip, ContextMenuStrip, and StatsStrip, * Itcan contain Button, Separator, Label, DiopDownButton, SplitButton, TextBox, and ComboBox. = It supports Allowitem Reorder, AllowMerge, Displayeditems, ImageL st, Items, MaxltemSize, Orientation, OverflowButton, Showltem ToolTips, Stretch, Text, and TextDirection properties, which are similar to MenuiStrip control as mention as above table. + Methods of ToolStrip control are sinilar to MenuStip control as above table 28 ToolStipt (4) StatusStrip + Ttrepresents a windows Status bar. + Itcan contain Status Label, DropDownButton, SplitButton, and ProgressBar. + Itdisplays information about an object being viewed on a Form, or information that relates to that operation of the abject within your application, = Itsupports AllowltemReorder, AllowMerge, Displayedtems, Image List, lems, MaxltemSize, Orientation, OverflowButton, Showltem ToolTips, Stretch, Text, and TextDirection properties, which are similar to MenuStrip control as mention in Menustrip topic, ‘TootstripStatust abel! jeu | An stmuatabe > Progresitar ene | Orepdowntutton 1B sotesuton Methods of StatuStrip control are similar to MenuStrip control as mention in MenuStrip topic. ¥ Default Event: Click) (5) ToolStrip Container z + Itprovides panels on each side ofthe form and a central panel that can hold one ‘or more controls } * Itis similar to SplitContainer, '* Ituses four docked side panels one central panel to create atypical arrangement. = Properties Property Description “ActiveControl [gets or Sets the active control on the container control “AutoScaleDimensions gets or sets the dimensions that the control was designed to ‘AutoScaleFactor It gets the sealing factor between the current and design-time automatic sealing dimensions, ‘AutoScale Mode It gets or sets the automatic scaling mode of the control ‘AutoScrollPosition It gets or sets the location of the auto-serell position. ‘ContentPanel It gets the center panel of the ToolStripContainer. Methods of ToolStripContainer control are similar to Panel control as mention in Panel control topic. Y Default Event: Click © scanned wth oxen Seamer 404- NET Programming + Dialoge Boxes = Visual Basic NET has built-in dialog boxes which allow user to create own Open, Save, Font, Color dialogs that are similar to other windows applications. They are available in Dialogs and Printing Tab of ToolBox. + The Dialog Boxes are as follows: (1) OpentileDiatog (2) SaveFileDialog Pointer (3) FonDialog Bl Colerdisieg (4) ColorDialog [BA FolderSrowserDiaiog B Printdiatog (5) PrintDiatog TG Fonbialog (5 PrintDocument (6) PrintPreviewDialog EI OpentleDialog [Q.PrintPreviewControt (1) PageSetupDialog _saveiedislog [F]_PrintPreviewialog (8) FolderBrowserDialog. (1) OpenFileDialog ‘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. Following is the Open File dialog box — ? [ElopenFieDialogt Properties of the OpenFileDialog Control Property Description ‘AddExtension (Gets or sets a value indicating whether the dialog box automatically adds an extension to a file name if the user omits the extension (CheckFileExists [Gets or sets a value indicating whether the dialog box displays a warning ifthe user ipecifies a file name that does not exist. DefaultExt (Gets or sets the default file name extension ‘FileName {Gets or sets a string containing the file name selected in the file dialog box. FileNames (Gets the file names ofall selected files in the dialog box. InitialDirectory [Gets or sets the initial directory displayed by the file dialog box. ‘Multiselect| _[Gets or sets a value indicating whether the dialog box allows m wo ‘ReadOnlyChecked _ [Gets or sets a value indicating whether the read-only check box is selected. ShowHelp (Gets or sets a value indicating whether the Help button is displayed inthe fle dialog box ShowReadOnly __|Gets or sets a value indicating whether the dialog box contains a read-only check box Title (Gets or sets the file dialog box title \ValidateNames Gets or sets a value indicating whether the dialog box accepts only valid Win32 file names. © scanned wth oxen Seamer 404- NET Programming Methods of the OpenFileDialog Control Method Name | Deseription ih [Opens the file selected by the user, with read-only permission. The fie is specified by the jopesle FileName property Reset [Resets all options to their default value. (OnFileOK Itraises the FileOk event. ShowDialog __|itruns a common dialog box with a default owner. Y Default Event: FileOk) (2) SaveFileDialog + The SaveFileDialog control prompts the user to select a location for saving a file and allows the wser to specify the name of the file to save data + The SaveFileDialog control class inherits from the abstract class FileDialog. Following is the Save File dialog box ~ [BlsaveFileDialogt Y Properties and methods of the Save File Dialog are the same as that of the Open File Di Y Default Event: FileOK() (3) FontDialog + Font Dislogis supported by the FomtDialog cass. It allow user to select a font size, face, style ee. Brondiiogt By default, the Color ComboBox is not shown on the Font dialog box. You should set the ShowColor property of the FontDialog, control to be True. Properties of the FontDialog Control Property Description [AllowVectorFonts _ Gets or sets a value indicating whether the dialog box allows vector font selections. (Gets or sets a value indicating whether the dialog box displays both vertical and horizontal fonts, [Allow VerticalFonts or only horizonal fons [Color (Gets or ses the selected font color. [Fone (Gets or sets the selected font. [MaxSize (Gets or sets the maximum point size a user ean select. [MinSize (Gets or sets the minimum point size a user can select. [ShowApply (Gets or sets a value indicating whether the dialog box contains an Apply button. [showColor (Gets or sets a value indicating whether the dialog box displays the color choice. (Gets or sets a value indicating whether the dialog box contains controls that allow the user to Ispecity strikethrough, underline, and text color options. [Shontelp {ets or sets value incating wheter te dialog box displays a Help baton {ShowEffects © scanned wth oxen Seamer 404-.NET Programming. Methods of the FontDialog Control Method Name Description [Reset Resets all options to their default values. [RunDialog | When overridden in a derived class, specifies a common dialog box. [ShowDialog _|_Runs a common dialog box with a default owner: Events of the FontDialog Control Event Description [Apply [Occurs when the Apply button on the font dialog box is clicked. (4) Color Dialogbox Color Dialog is supported by the FomtDialog class and it allow user to select a color. = The ColorDialog control class represents a common dialog box that displays available colors along with controls that enable the user to define custom colors + The main property of the ColorDialog control is Color, which returns a Color object. Following is the Color dialog box ~ Bl cotorDiatogt Properties of the ColorDialog Control Property Description [Atowattopen [645 0" 8 value indicating wheter the user can se the lg box to dis cstom la [Gets or sets @ value indicating whether the dialog box displays all available colors inthe nyColor y let of basic colors [Color |[Gets or sets the color selected by the user. [CustomColors [Gets or sets the set of custom colors shown in the dialog box. [ShowHelp [Gets oF sets a value indicating whether a Help button appears in the color dialog box i [Gets or sts a value indicating whether the dialog box will restrict users to selecting solid SsotidColorOnty [os only Methods of the ColorDialog Control ‘Method Name Description Resets all options to their default values, the last selected color to black, and the custom ial lcolors to their default values. [RunDialog [When overridden ina derived class, specifies a common dialog box. [ShowDialog [Runs a common dialog box with a default owner. [OnHelpRequest __ [lt raises the HelpRequest event. Events of the ColorDialog Control Event & Description [HetpRequest___ [Occurs when the user clicks the Help button on a common dialog box. © scanned wth oxen Seamer 404-.NET Programming (5) FolderBrowserDialog + FolderBrowserDialog is supported by the FolderBrowserDialog class and it prompts the user to select a folder: Boeke Gp ubares ob teweriy Baten A) FolderBronseDialog! +8 compte Bisaie) erties) Savor cal Properties of the FolderBrowserDialog Control Property Description [RootFolder It gets or sets the root folder where the browsing starts from. [SelectedPath it gots or sets the path selected by the user. It gets or sets a value indicating whether the new folder button appears in the folder browser dialog box. ¥ Italso has OntleipR equest, Reset and ShowDialog methods same as ColorDialog and FontDialog, OpenFileDialog, SaveFileDialog + Defult EventHelpRequest() (6) PrintDialog Printing is the one of the common tasks during application development. ‘The NET Framework provides excellent support for printing documents Print Dialog is supported by the PrintDialog class and it allow user to print document. It lets user to select a printer and choose which sections of the document to print from a Windows Forms application. + Following is the Print dialog box ~ |ShowNewFolderButton| RBMicnnt Peete POF peels) Ronee ge [2 PrintDialogt © scanned wth oxen Seamer 404- NET Programming Properties of the PrintDialog Control Property Description [AtlowCurrentPage | Gets or sets a value indicating whether the Current Page option button is displayed. [AlowPrin¢foFile_|Gets or sets a value indicating whether the Print to file check box is enabled. [AtlowSelection __ | Gets or sets a value indicating whether the Selection option button is enabled. [AtlowSomePages __|Gets or sets a value indicating whether the Pages option button is enabled. [Document [Gets or sets a value indicating the PrintDocument used to obtain PrinterSettings. [PrinterSettings Gets or sets the printer settings the dialog box modifies. [PrintToFii [Gets or sets a value indicating whether the Print to file check box is selected, [ShowHelp (Gets or sets a value indicating whether the Help button is displayed. [ShowNetwork Gets or sets a value indicating whether the Network button is displayed ‘Methods of the PrintDialog Control [Method Name| Deseription [Reset Resets all options to their default values. [RunDialog | When overridden in a derived class, specifies a common dialog box. [ShowDialog _|Runs a common dialog box with a default owner. 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 pr 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, Exampl t settings including page Open File Dialog_Button_ClickQ) OpenFileDialog! ShowDialog() Save File Dialog_Button_Click() SaveFileDialog! ShowDialog)) Font Dialog_Button_ClickQ, FontDialog! ShowDialog() Color Dialog_Button_Click() ColorDialog1.ShowDialog0, Folder Browser Dialog Button_Click() FolderBrowserDialogl.ShowDialog() Print Dialog Button_Click() PrintDialogl.ShowDialog() © scanned wth oxen Seamer 404- NET Programming Example: (Notepad Simulation) Toots abl Flopentieoieo! —fortalog! -FloesreneeOslogi ESaeFiedulog? A colaraiogt Lisuusseiot A contentenuseipt DPanditgt 5 Menusipt © scanned wth oxen Seamer 404 .NET Programming Cod jotepad Load) ‘ToolStripStatusL abel Tex ToolStripProgressBarl. Value oading." 40 New: IfRichTextBox!.Text.Length > 0 Then If MsgBox(" Save File 7", MsaBoxSiyle.Information + MseBoxSiyle:YesNo) = MsgBoxResult.Yes Then If SaveFileDialog! ShowDialog = Windows.Forms.Dialoaltesull,OK Then RichiTextBoxl. SaveFile(SaveFileDialogl. FileName) End If Else RichTextBox! Clear) Me Text = "Untitled-Notepad” End If End It Open: If OpenFileDialogl.ShowDialog ~ Windows Forms.Dialoalesull, OK Thea RichTextBox! LoadFite(OpenFileDialogl FileName) End If Save: If SaveFileDialog! ShowDialog = Windows. Forms,Dialox!esul.OK Then RichTextBox1.SaveFile SaveFileDialog] FileName) End If Exit If RichTextBox|Text.Length > 0 Then If MsgBox("Do you Really want Exit Then MsgBoxStyle.tnformation + MsgBoxStyle. YesNo) = MsgBoxResull. Yes If SaveFileDialogl. ShowDialog = Windows. Forms.DialogResul.OK Then RichTextBoxlSaveFile(SaveFileDialogl. FileName) End If EndIf Else Me.Close() End If Undo: RichTextBox!.Undo) Cut RichTextBoxl.Cut() Pas RichTextBox1.Paste() Copy: RichTextBox!.Copy() Dele RichTextBox1.SelectedText SelectAll: RichTextBox!.SelectAIIQ, les RichTextBox!.Clear() © scanned wth oxen Seamer 404- NET Programming ‘Time & Date: RichTextBoxl.SelectedText = Date Now Font: If FonDialog! ShowDialog = Windows.Forms.DialogResult OK Then RichTextBoxl SelectionFont = FontDialogl.Font End If WordWrap: If RichTextBox1.WordWrap = True Then RichTextBox1. WordWrap = False Else RichTextBox1.WordWrap = True End If Forecol If ColorDialog! ShowDialog = Windows.Forms.Disloglesull.K Then RichTextBox! ForeColor = ColorDialogl Color End If PrintDialogl.ShowDialog() 3.3. Exception Handling in VB.NET * Error: Error means bug that means when you compile or tuna program, abnormal situation may raise which is known as error. ‘There are different types of Error: 1, Syntax Error: The error raised by misspelled keywords oF variables is called Syntax Error. ‘Compiler will normally catch these errors while you are coding or after the compilation of program. 2..Logle Error: Due to the mistake present in the sequence of statements, code does not act as expected. This type of error is called Logic Error. 3. Runtime Error: The error which occurs when the code is executing, i ealled Runtime Error. * Exception Exceptions are run-time errors, which ae raised when program is running. There are wo ways to handle errors that, ecur at runtime: (1) Unstructured exception handling (2) Structured exception handling Structured Exception Handling: * It is implemented with Try...Catch... Finally statement, which is divided into a Try block, optional Catch blocks and an optional Finally block. ‘The Try block contains code where exceptions can occur; the Catch block contains code to handle the exceptions that occur. * [fan exception occurs in the Try block the code throws the exception, soit can be caught and handled by the appropriate Catch statement, ‘Afier the rest ofthe statement finishes, execution is always passed to the Finally block: © scanned wth oxen Seamer

You might also like