Programming Interface Controls with VB Net User Interface

Programming Interface Controls with VB. Net

User Interface Controls • Form • Message. Box • Common Controls: – Button, Text. Box, Masked. Text. Box, List Box, Option Button, Check Box, Checked. List. Box, numeric. Up. Down • Container controls: – Group. Box, etc. • Others: – Timer – Tool. Tip – Components

Form • Form is defined as a class. • Methods: – – Show, Show. Dialog: Open a form Activate, Focus: Make an opened form get focus Hide, Close Ex. • Me. Hide, Me. Close Note: Closing a form is equivalent to delete a form. • Events: – Load, Activated, De. Activate, Closing, Closed

Multiple Forms Two forms: Form 1, Form 2 To Open Form 2 from Form 1: Standard but troublesome way to open a form: Must create an instance of the form class by using the keyword New to access the form. Dim f 2 As New Form 2() f 2. Show() Open Form 2 as a Modal form: f 2. Show. Dialog() .

• Modeless form: Other forms can receive input focus while this form remains active. – Form. Name. Show() • Modal form: No other form can receive focus while this form remains active. – Form. Name. Show. Dialog() • Demo: Problem with the Show method

Using the Default Instances of Forms to Open a Form • form. Name. Show, form. Name. Show. Dialog • Always bring up the same underlying default instance of the form. – Example: Form 2. Show. Dialog

Control Start. Up Form • Click: – Project/Properties/Application/Start. Up Form – Then select the form

Sharing. Variables Among Forms • Define these variables with project-level scope in a module using the Public keyword: – Module 1 – Public test. Var As Integer – End Module – Note: Use Project/Add Module to add a module.

Modules • A file contains code such as: – Variable declarations – Procedures and functions • Variables and procedures used by more than one form should store in a module. • Global variables: Public

Message. Box. Show(message) Message. Box. Show(message, Caption, Buttons) Note: 1. In each format, arguments are positional and required. 2. This object returns a Dialog. Result data type. Possible values for a Dialog. Result data type are: Abort, Cancel, Ignore, None, OK, Re. Try, and Yes. To test the return value: Dim Return. Val as Dialog. Result Return. Val=Message. Box(“hello”, …. . ) If Return. Val=Dialog. Result. OK…

Form Closing Event Example Private Sub Form 10_Form. Closing(By. Val sender As Object, By. Val e As System. Windows. Form. Closing. Event. Args) Handles Me. Form. Closing If Message. Box. Show("Are you sure? ", "Warning", Message. Box. Buttons. Yes. No) = Dialog. Result. Yes Then e. Cancel = False Else e. Cancel = True End If End Sub Note: Event procedure arguments: sender: object that triggers the event. e: event object

Text Box • Useful properties – – – – Back. Color, Border. Style Read. Only Enable Visible Password Character Multiline Scroll. Bar Text • Useful events – Text. Changed: default event – Validating – useful for validating data entered in the box

Input Validation • Numbers are checked to ensure they are: – – Within a range of possible values Reasonableness Not causing problems such as division by 0. Containing only digits • Is. Numeric • Texts are checked to ensure correct format. – Phone #, SSN. • Required field • Textbox: – Set Cause. Validation property to true. – Use the Validating event: • Triggered just before the focus shifts to other control.

Text. Box Validating Event Private Sub Text. Box 1_Validating(By. Val sender As Object, By. Val e As System. Component. Model. Cancel. Event. Args) Handles Text. Box 1. Validating If Not Is. Numeric(Text. Box 1. Text) Then e. Cancel = True Messag. Box. Show("enter digits only") Else Message. Box. Show("good") End If End Sub Note: Why not use the Text. Changed event?

String Methods • • To. Upper, To. Lower Length – Number of characters Trim. Start, Trim. End, Trim Substring(Start), Substring(Start, length) • Index. Of(Search. String), Index. Of(Search. String, Start) – 0 based index – Case-sensitive • e. Name=“David” • Position=e. Name. Index. Of(“d”) – Return – 1 if the search. String is not found. • Note: Text property of a Textbox has all the string methods. – Ex. Text. Box 1. Text. Substring(0, 2)

Example: Extract the firstname and the lastname from a fullname • • Dim index. Space As Integer Dim first. Name, last. Name As String index. Space = Text. Box 1. Text. Index. Of(" ") first. Name = Text. Box 1. Text. Substring(0, index. Space) last. Name = Text. Box 1. Text. Substring(index. Space + 1) Message. Box. Show(first. Name) Message. Box. Show(last. Name)

Validate SSN Format Private Sub Text. Box 1_Validating(By. Val sender As Object, By. Val e As System. Component. Model. Cancel. Event. Args) Handles Text. Box 1. Validating Dim correct As Boolean = True If Not Is. Numeric(Text. Box 1. Text. Substring(0, 3)) Or _ Not Is. Numeric(Text. Box 1. Text. Substring(4, 2)) Or _ Not Is. Numeric(Text. Box 1. Text. Substring(7, 4)) Then correct = False End If If Text. Box 1. Text. Substring(3, 1) <> "-" Or Text. Box 1. Text. Substring(6, 1) <> "-" Then correct = False End If If correct Then Message. Box. Show("perfect format") Else e. Cancel = True Message. Box. Show("not correct format") End If End Sub

Group Box • It is a container control. • Controls in a Group Box should move with the box.

Radio Button • Radio buttons must be grouped together inside a container such as a Group. Box or a form. • When the user selects an option all other options in the same group are deselected. • Properties: – Checked: True/False. • Default button: Set the Checked property to true at the design time. • Events: – Checked. Changed

Radio. Button Example If radio. Button 1. Checked=true then textbox 1. text=“You select radio button 1” Else. If radio. Button 2. Checked=true then textbox 1. text=“You select radio button 2” Else textbox 1. text=“You select radio button 3” End If

Check Box • Check boxes do not belong to a group even when they are grouped in a Group Box. • Checked property and checked. Changed event

Check Box Example 1 Private Sub Check. Box 1_Checked. Changed(By. Val sender As System. Object, By. Val e As System. Event. Args) Handles Check. Box 1. Checked. Changed If Check. Box 1. Checked = True Then Message. Box. Show(“check chk 1") Else Message. Box. Show("uncheck chk 1") End If End Sub

Check Box Example 2 Dim msg as String Msg=“You choose “ If check. Box 1. checked=true then msg=msg & “check box 1” End If If check. Box 2. checked=true then msg=msg & “check box 2” End If If check. Box 3. checked=true then msg=msg & “check box 3” End If Note: Cannot put these three conditions in a If …Else. If block.

List Box • Useful properties – Items: The items in the list. Box. It is a collection strcture. Items can be entered at the design time or entered in code. • 0 -based index – Selection. Mode: one or multi selection – Selected. Item(s) – Multi. Column • Methods – Add – Clear • Event: Selected. Index. Change

List Box Example Private Sub Form 1_Load(By. Val sender As Object, By. Val e As System. Event. Args) Handles My. Base. Load Text. Box 1. Clear() Text. Box 2. Clear() List. Box 1. Items. Add("Apple") List. Box 1. Items. Add("Orange") List. Box 1. Items. Add("Banana") List. Box 1. Items. Add("Strawberry") Text. Box 2. Text = List. Box 1. Items. Count. To. String End Sub Private Sub List. Box 1_Selected. Index. Changed(By. Val sender As System. Object, By. Val e As System. Event. Args) Handles List. Box 1. Selected. Index. Changed Text. Box 1. Text = List. Box 1. Selected. Item End Sub

List Items Collections • Methods: – ADD: List. Box 1. Items. Add("Apple") – Item: Retrieve an object from Items • List. Box 1. Items. Item(Index) or List. Box 1. Items(Index) • 0 -based index – Insert: List. Box. Items. Insert(Index, item) – Remove: Delete an object with a position index or key. • List. Box. Items. Remove(Item) • List. Box. Items. Remove. At(Index) – Clear: List. Box. Items. Clear() – Count: Return the number of objects in a collection. • List. Box. Items. Count

Selected Item’s Value • Demo: – Select interest rate from a list box: • 5% -> 0. 05 – – – – – Dim int. Rate As Double Select Case List. Box 1. Selected. Item Case "5% " int. Rate = 0. 05 Case “ 6%” int. Rate = 0. 06 Case “ 7%” int. Rate = 0. 07 End Select

Structured Error Handling Try result = Val(Text. Box 1. Text) / Val(Text. Box 2. Text) Text. Box 3. Text = result. To. String Catch except As Divide. By. Zero. Exception Message. Box. Show(except. Message) Catch except As Exception Message. Box. Show(except. Message) Finally Message. Box. Show("I get exdecuted, no matter what") End Try

Using One Event Procedure to Handle Many Events Private Sub Btn. Click(By. Val sender As System. Object, By. Val e As System. Event. Args) Handles Button 1. Click, Button 2. Click, Button 3. Click If sender. name = "Button 1" Then Message. Box. Show("btn 1") Else. If sender. name = "Button 2" Then Message. Box. Show("Btn 2") Else Message. Box. Show("btn 3") End If End Sub Note 1: Controls’ Tag property Note 2: Late binding

Programming Interface Controls with C#

Working with Form • To close a form: – this. Close(); • To choose the startup form: Change the code in Program. cs – Example, to start from form 2 instead of form 1, use this code: • Application. Run(new Form 2());

Form Closing Event private void Form 2_Form. Closing(object sender, Form. Closing. Event. Args e) { if (Message. Box. Show("Are you sure? ", "Warning", Message. Box. Buttons. Yes. No) == Dialog. Result. Yes) { e. Cancel = false; } else { e. Cancel = true; } }

Text. Box Validating Event Example: Testing for digits only There is no equivalent Is. Numeric function in C#. This example uses the Double. Parse method trying to convert the data entered in the box to double. If fail then it is not numeric. private void text. Box 1_Validating(object sender, Cancel. Event. Args e) { try { Double. Parse(text. Box 1. Text); e. Cancel = false; } catch { e. Cancel = true; Message. Box. Show("Enter digits only"); } }

Extract First Name and Last Name int index. Space; string first. Name, last. Name ; index. Space = text. Box 2. Text. Index. Of(" "); first. Name = text. Box 2. Text. Substring(0, index. Space); last. Name = text. Box 2. Text. Substring(index. Space + 1); Message. Box. Show(first. Name); Message. Box. Show(last. Name);

Creating a Boolean My. Is. Numeric Function private Boolean My. Is. Numeric(string s) { try { Double. Parse(s); return true; } catch { return false; } }

Using My. Is. Numeric Function to Vaidate SSN Format private void button 3_Click(object sender, Event. Args e) { bool correct = true; if (! My. Is. Numeric(text. Box 2. Text. Substring(0, 3)) || ! My. Is. Numeric(text. Box 2. Text. Substring(4, 2)) || ! My. Is. Numeric(text. Box 2. Text. Substring(7, 4)) ) { correct = false; } if (text. Box 2. Text. Substring(3, 1) != "-" || text. Box 2. Text. Substring(6, 1) != "-" ) { correct = false; } if (correct) { Message. Box. Show("perfect format"); } else { Message. Box. Show("not correct format"); } }

Working with Radiobuttons, Listbox • Create a form with 2 radiobuttons. When radiobutton 1 is selected, populate a listbox with fruit names. ; otherwise populate the listbox with vegetable names. Then, dsplay the fruit or vegetable’s name in a textbox when user select an item from the listbox.

private void radio. Button 1_Checked. Changed(object sender, Event. Args e) { if (radio. Button 1. Checked) { list. Box 1. Items. Clear(); list. Box 1. Items. Add("Apple"); list. Box 1. Items. Add("Orange"); list. Box 1. Items. Add("Banana"); list. Box 1. Items. Add("Strawberry"); list. Box 1. Items. Add("Papaya"); } if (radio. Button 2. Checked) { list. Box 1. Items. Clear(); list. Box 1. Items. Add("Spinach"); list. Box 1. Items. Add("Brocoli"); list. Box 1. Items. Add("Tomato"); list. Box 1. Items. Add("Lettuce"); list. Box 1. Items. Add("Cabbage"); } } private void list. Box 1_Selected. Index. Changed(object sender, Event. Args e) { text. Box 1. Text = list. Box 1. Selected. Item. To. String(); }

Create a Loan Payment Form

Using VB. Net’s PMT Function • Add a reference to Microsoft Visual Baisc – From the Solution Explorer, right-click the References node, then click Add Reference – From the. Net tab, select Microsoft Visual Baisc – Add this code to the form: • using Microsoft. Visual. Basic;

private void button 1_Click(object sender, Event. Args e) { double loan, term, rate, payment; loan = Double. Parse(text. Box 1. Text); if (radio. Button 1. Checked) { term = 15; } else { term = 30; } switch (list. Box 1. Selected. Index) { case 0: rate=. 05; break; case 1: rate=. 06; break; case 2: rate =. 07; break; case 3: rate =. 08; break; case 4: rate =. 09; break; default: rate = 0. 05; break; } payment = Financial. Pmt(rate / 12, term * 12, -loan); text. Box 2. Text = payment. To. String(); }

How to Use VB’s Is. Numeric Function • Add a reference to Microsoft Visual. Basic Compatibility namespace. • Then, add this code to the form: – using Microsoft. Visual. Basic; • Microsoft. Visual. Basic. Information class contains the Is. Numeric function if (! Information. Is. Numeric(text. Box 1. Text)) { e. Cancel = true; Message. Box. Show("Enter digits only"); } else { e. Cancel=false; }

Combo. Box • Allows the user to type text directly into the combo box. • Use the Text property to get entered item: – Combo. Box 1. Text – The index for an entered item is – 1. • Search an item in the list: Combo. Box 1. Items. Index. Of(“search text”) – Found: return the index of the search text. – Not found: return – 1. • How to add an entered item to the list?

Tool. Tip • Add Tool. Tip to form. • Use controls’ Tool. Tip. On property to enter tip.

Timer • Properties: • Enabled -- must set to True. • Interval • Tick Event private void timer 1_Tick(object sender, Event. Args e) { text. Box 1. Text = System. Date. Time. Now. To. String(); }

Use a Timer to Close a Form int counter = 0; private void timer 1_Tick(object sender, Event. Args e) { if (counter > 50) { this. Close(); } }

Using One Event Procedure to Handle Many Events private void button. Click(object sender, Event. Args e) { if (sender. To. String(). Contains("0")) { Phone = Phone + "0"; } else if (sender. To. String(). Contains("1")) { Phone = Phone + "1"; } else { Phone = Phone + "2"; } text. Box 1. Text = Phone; }
- Slides: 47