Programming Interface Controls with VB.Net. User Interface Controls Form MessageBox, InputBox Common Controls: –Button, TextBox, MaskedTextBox, List Box,

Slides:



Advertisements
Similar presentations
Lists, Loops, Validation, and More
Advertisements

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 1 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis.
Microsoft Visual Basic: Reloaded Chapter Seven More on the Repetition Structure.
Practical Programming COMP153-08S Lecture: Repetition Continued.
Creating Custom Controls ISYS 512/812. Inheritance The process in which a new class can be based on an existing class, and will inherit that class’s interface.
VB.NET User Interface Controls
VB.Net Loops.
Programming Based on Events
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1.
VB.Net Introduction - 2. Counter Example: Keep track the number of times a user clicks a button Need to declare a variable: Dim Counter As Integer Need.
Programming Interface Controls with VB.Net. User Interface Controls Form MessageBox Common Controls: –Button, TextBox, MaskedTextBox, List Box, Option.
Multiple Forms & Procedures. Form Methods: –Show, Hide, Activate, Close Events: –Load, Activated, Closing, Closed.
VB.Net Decisions. The If … Then Statement If condition Then Statements End If If condition Then Statements Else Statements End If Condition: –Simple condition:
Coding ADO.NET Objects: Connection, Command, DataReader.
VB.Net Decisions. The If … Then Statement If condition Then Statements End If If condition Then Statements Else Statements End If Condition: –Simple condition:
VB.Net Loops. Loop FOR index – start TO end [STEP step] [statements] [EXIT FOR] NEXT index DO [{WHILE| UNTIL} condition] [statements] [EXIT DO] LOOP.
Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements.
Microsoft Visual Basic 2005 CHAPTER 8 Using Procedures and Exception Handling.
Tutorial 7: Sub and Function Procedures1 Tutorial 7 Sub and Function Procedures.
Visual Basic Fundamental Concepts. Integrated Development Enviroment Generates startup form for new project on which to place controls. Features toolbox.
Microsoft Visual Basic 2012 Using Procedures and Exception Handling CHAPTER SEVEN.
Microsoft Visual Basic 2008 CHAPTER 8 Using Procedures and Exception Handling.
Microsoft Visual Basic 2008 CHAPTER NINE Using Arrays and File Handling.
Multiple Forms, Standard Modules, And Menus
Multiple Forms and Standard Modules
Chapter 6 Understanding the Structure of an Application: Procedures, Modules, and Classes.
Chapter 7 Decision Making. Class 7: Decision Making Use the Boolean data type in decision-making statements Use If statements and Select Case statements.
C# Introduction ISYS 350. Visual Studio 2012 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows.
Visual Basic.NET Comprehensive Concepts and Techniques Chapter 4 Working with Variables, Constants, Data Types, and Expressions.
C# Introduction ISYS 512. Visual Studio 2013 Demo Start page: New project/ Open project/Recent projects Starting project: File/New Project/ –C# –Windows.
Programming Interface Controls ISYS 350. User Interface Controls Form MessageBox Common Controls: –Button, TextBox, MaskedTextBox, List Box, Option Button,
VB Procedures. Procedures. Sub procedure: Private/Public Sub SubName(Arguments) … End Sub Private: Can only be accessed by procedures in the same form.
Loops ISYS 350. A Box of Chocolate Repeat this process until box is empty: – Take one chocolate from the box – Eat the chocolate – Box has more chocolate?
Decision Structure - 1 ISYS 350. Decision: Action based on condition Examples Simple condition: – If total sales exceeds $300 then applies 5% discount;
CS0004: Introduction to Programming Project 1 – Lessons Learned.
Programming Interface Controls ISYS 350. User Interface Controls Form MessageBox Common Controls: –Button, TextBox, MaskedTextBox, List Box, Option Button,
Loops ISYS 350. Compute the sum of a list of numbers: Example: 5, 2, 10, 8, 4 Process: Sum= 0 Get a number from the list Sum = Sum + the number Repeat.
CS 101 Test 2 Study Guide Acronyms RAD - Rapid Application Development IDE - Integrated Development Environment GUI - Graphical User Interface VB - Visual.
Programming Interface Controls ISYS 350. User Interface Controls Form MessageBox Common Controls: –Button, TextBox, MaskedTextBox, List Box, Option Button,
Created by Alia Al-Abdulkarim 2008 Visual Basic Vs. Java.
Loops ISYS 350. Two Types of Loops while loop for loop.
Decision Structure - 1 ISYS 350. Decision: Action based on condition Examples Simple condition: – If total sales exceeds $300 then applies 5% discount;
Introduction to Methods ISYS 350. Methods Methods can be used to break a complex program into small, manageable pieces – This approach is known as divide.
Visual Basic Declaring Variables Dim x as Integer = 0 In the statement above, x is being declared as an Integer (whole number) and is initialised.
Programming Interface Controls ISYS 350. User Interface Controls Form MessageBox Common Controls: –Button, TextBox, MaskedTextBox, List Box, Option Button,
Programming Interface Controls ISYS 350. User Interface Controls Form MessageBox Common Controls: –Button, TextBox, MaskedTextBox, List Box, Option Button,
COMPUTER PROGRAMMING I Apply Procedures to Develop List Box and Combo Box Objects.
Array, ArrayList and List ISYS 350. Array An array allows you to store a group of items of the same type together. Processing a large number of items.
VB.NET User Interface Controls. VB User Interface Objects Form InputBox, MessageBox Standard Controls: –TextBox, MaskedTextBox, List Box, Option Button,
C# Introduction ISYS 350.
Visual Basic Fundamental Concepts
Apply Procedures to Develop Menus, List Box and Combo Box Objects
Decision Structure - 1 ISYS 350.
Loops ISYS 350.
Apply Procedures to Develop Menus, List Box and Combo Box Objects
Programming Interface Controls
Programming Interface Controls
C# Introduction ISYS 350.
Decision Structure - 1 ISYS 350.
C# Introduction ISYS 350.
Visual Basic..
Decision Structures ISYS 350.
CIS16 Application Development and Programming using Visual Basic.net
CIS 16 Application Development Programming with Visual Basic
Lecture Set 10 Windows Controls and Forms
Decision Structure - 1 ISYS 350.
Based on Murach Chapter 10
Decision Structure - 1 ISYS 350.
Visual C# - GUI and controls - 1
Programming Interface Controls
Presentation transcript:

Programming Interface Controls with VB.Net

User Interface Controls Form MessageBox, InputBox Common Controls: –Button, TextBox, MaskedTextBox, List Box, Option Button, Check Box, CheckedListBox, numericUpDown Container controls: –GroupBox, etc. Others: –Timer –ToolTip –Components

Form Form is defined as a class. Methods: –Show, ShowDialog: Open a form –Activate, Focus: Make an opened form get focus –Hide, Close –Ex. Me.Hide, Me.Close Events: –Load, Activated, DeActivate, Closing, Closed

Multiple Forms Two forms: Form1, Form2 To Open Form2 from Form1: 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 f2 As New Form2() f2.Show() Open Form2 as a Modal form: f2.ShowDialog().

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

Using the Default Instances of Forms to Open a Form formName.Show, formName.ShowDialog Always bring up the same underlying default instance of the form. –Example: Form2.ShowDialog

Control StartUp Form Click: –Project/Properties/Application/StartUp Form –Then select the form

SharingVariables Among Forms Define these variables with project-level scope in a module using the Public keyword: –Module Module1 – Public testVar 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

MessageBox MessageBox.Show(message) MessageBox.Show(message, Caption) MessageBox.Show(message, Caption, Buttons) Note: 1. In each format, arguments are positional and required. 2. This object returns a DialogResult data type. Possible values for a DialogResult data type are: Abort, Cancel, Ignore, No, None, OK, ReTry, and Yes. To test the return value: Dim ReturnVal as DialogResult ReturnVal=MessageBox(“hello”, …..) If ReturnVal=DialogResult.OK…

Form Closing Event Example Private Sub Form10_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing If MessageBox.Show("Are you sure?", "Warning", MessageBoxButtons.YesNo) = DialogResult.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

InputBox Dim counter = 0, sum = 0, myInt As Integer myInt = InputBox("Enter an integer") Do While counter <= myInt sum = sum + counter counter += 1 Loop MessageBox.Show("The sum is: " + sum.ToString)

Text Box Useful properties –BackColor, BorderStyle –ReadOnly –Enable –Visible –Password Character –Multiline –ScrollBar –Text Useful events –TextChanged: 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 IsNumeric Texts are checked to ensure correct format. –Phone #, SSN. Required field Textbox: –Set CauseValidation property to true. –Use the Validating event: Triggered just before the focus shifts to other control.

TextBox Validating Event Private Sub TextBox1_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating If Not IsNumeric(TextBox1.Text) Then e.Cancel = True MessagBox.Show("enter digits only") Else MessageBox.Show("good") End If End Sub Note: Why not use the TextChanged event?

String Methods ToUpper, ToLower Length – Number of characters TrimStart, TrimEnd, Trim Substring(Start), Substring(Start, length) IndexOf(SearchString), IndexOf(SearchString, Start) –0 based index –Case-sensitive eName=“David” Position=eName.IndexOf(“d”) –Return –1 if the searchString is not found. Note: Text property of a Textbox has all the string methods. –Ex. TextBox1.Text.Substring(0,2)

Example: Extract the firstname and the lastname from a fullname Dim indexSpace As Integer Dim firstName, lastName As String indexSpace = TextBox1.Text.IndexOf(" ") firstName = TextBox1.Text.Substring(0, indexSpace) lastName = TextBox1.Text.Substring(indexSpace + 1) MessageBox.Show(firstName) MessageBox.Show(lastName)

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 GroupBox 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: –CheckedChanged

RadioButton Example If radioButton1.Checked=true then textbox1.text=“You select radio button 1” ElseIf radioButton2.Checked=true then textbox1.text=“You select radio button 2” Else textbox1.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 checkedChanged event

Check Box Example 1 Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged If CheckBox1.Checked = True Then MessageBox.Show(“check chk1") Else MessageBox.Show("uncheck chk1") End If End Sub

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

List Box Useful properties –Items: The items in the listBox. It is a collection strcture. Items can be entered at the design time or entered in code. 0-based index –SelectionMode: one or multi selection –SelectedItem(s) –MultiColumn Methods –Add –Clear Event: SelectedIndexChange

List Box Example Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load TextBox1.Clear() TextBox2.Clear() ListBox1.Items.Clear() ListBox1.Items.Add("Apple") ListBox1.Items.Add("Orange") ListBox1.Items.Add("Banana") ListBox1.Items.Add("Strawberry") TextBox2.Text = ListBox1.Items.Count.ToString End Sub Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged TextBox1.Text = ListBox1.SelectedItem End Sub

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

Selected Item’s Value Demo: –Select interest rate from a list box: 5% -> 0.05 – Dim intRate As Double – Select Case ListBox1.SelectedItem – Case "5% " – intRate = 0.05 – Case “6%” – intRate = 0.06 – Case “7%” – intRate = 0.07 – End Select

Structured Error Handling Dim result As Double Try result = CDbl(TextBox1.Text) / CDbl(TextBox2.Text) TextBox3.Text = result.ToString Catch except As Exception MessageBox.Show(except.Message) End Try

Using One Event Procedure to Handle Many Events Private Sub BtnClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click, Button3.Click If sender.name = "Button1" Then MessageBox.Show("btn 1") ElseIf sender.name = "Button2" Then MessageBox.Show("Btn2") Else MessageBox.Show("btn3") 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 form2 instead of form1, use this code: Application.Run(new Form2());

Form Closing Event private void Form2_FormClosing(object sender, FormClosingEventArgs e) { if (MessageBox.Show("Are you sure?", "Warning", MessageBoxButtons.YesNo) == DialogResult.Yes) { e.Cancel = false; } else { e.Cancel = true; }

Modeless form: Other forms can receive input focus while this form remains active. –FormName.Show() Modal form: No other form can receive focus while this form remains active. –FormName.ShowDialog()

Multiple Forms Two forms: Form1, Form2 To Open Form2 from Form1: 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. Form2 f2 = new Form2 (); Open Form2 as a Modeless form: f2.Show (); Open Form2 as a Modal form: f2.ShowDialog(); Demo: Problem with the Show method.

Interactive Input using VB’s InputBox Statement Add a reference to Microsoft Visual Baisc: 1. From the Solution Explorer, right-click the References node, then click Add Reference 2. From the.Net tab, select Microsoft Visual Baisc 3. Add this code to the form: using Microsoft.VisualBasic; int myint; myint= int.Parse(Interaction.InputBox("enter a number:")); MessageBox.Show(myint.ToString()); Example of using InputBox :

Accumulator Find the sum of all numbers between 1 and N. int N, Sum, Counter = 1; N = int.Parse(Interaction.InputBox("enter an integer:")); Sum = 0; while (Counter <= N) { Sum += Counter; ++Counter; } MessageBox.Show(Sum.ToString()); Method 1:

TextBox Validating Event Example: Testing for digits only There is no equivalent IsNumeric 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 textBox1_Validating(object sender, CancelEventArgs e) { try { Double.Parse(textBox1.Text); e.Cancel = false; } catch { e.Cancel = true; MessageBox.Show("Enter digits only"); }

Extract First Name and Last Name int indexSpace; string firstName, lastName ; indexSpace = textBox2.Text.IndexOf(" "); firstName = textBox2.Text.Substring(0, indexSpace); lastName = textBox2.Text.Substring(indexSpace + 1); MessageBox.Show(firstName); MessageBox.Show(lastName);

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

Using the MyIsNumeric Function private void textBox1_Validating(object sender, CancelEventArgs e) { if (!MyIsNumeric(textBox1.Text)) { MessageBox.Show("Enter digit only"); e.Cancel=true; }

Working with Radiobuttons, Listbox Create a form with 2 radiobuttons. When radiobutton1 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 radioButton1_CheckedChanged(object sender, EventArgs e) { if (radioButton1.Checked) { listBox1.Items.Clear(); listBox1.Items.Add("Apple"); listBox1.Items.Add("Orange"); listBox1.Items.Add("Banana"); listBox1.Items.Add("Strawberry"); listBox1.Items.Add("Papaya"); } if (radioButton2.Checked) { listBox1.Items.Clear(); listBox1.Items.Add("Spinach"); listBox1.Items.Add("Brocoli"); listBox1.Items.Add("Tomato"); listBox1.Items.Add("Lettuce"); listBox1.Items.Add("Cabbage"); } private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { textBox1.Text = listBox1.SelectedItem.ToString(); }

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.VisualBasic;

private void button1_Click(object sender, EventArgs e) { double loan, term, rate, payment; loan = Double.Parse(textBox1.Text); if (radioButton1.Checked) { term = 15; } else { term = 30; } switch (listBox1.SelectedIndex) { 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); textBox2.Text = payment.ToString(); }

How to Use VB’s IsNumeric Function Add a reference to Microsoft VisualBasic Compatibility namespace. Then, add this code to the form: –using Microsoft.VisualBasic; Microsoft.VisualBasic.Information class contains the IsNumeric function if (! Information.IsNumeric(textBox1.Text)) { e.Cancel = true; MessageBox.Show("Enter digits only"); } else { e.Cancel=false; }

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

ToolTip Add ToolTip to form. Use controls’ ToolTipOn property to enter tip.

Timer Properties: Enabled -- must set to True. Interval Tick Event private void timer1_Tick(object sender, EventArgs e) { textBox1.Text = System.DateTime.Now.ToString(); }

Use a Timer to Close a Form int counter = 0; private void timer1_Tick(object sender, EventArgs e) { counter+=1; if (counter > 50) { this.Close(); }

Using One Event Procedure to Handle Many Events private void buttonClick(object sender, EventArgs e) { if (sender.ToString().Contains("0")) { Phone = Phone + "0"; } else if (sender.ToString().Contains("1")) { Phone = Phone + "1"; } else { Phone = Phone + "2"; } textBox1.Text = Phone; }