0% found this document useful (0 votes)
13 views20 pages

VB Prac

The document provides a comprehensive overview of Visual Basic .NET exercises, including variable declaration, string manipulation, and control structures. It also covers SQL basics, including Data Definition Language (DDL) and Data Manipulation Language (DML), with examples of SQL statements for creating, altering, and deleting tables, as well as querying data. Additionally, it discusses accessing multiple tables and creating calculated values in SQL.

Uploaded by

paulas2014
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views20 pages

VB Prac

The document provides a comprehensive overview of Visual Basic .NET exercises, including variable declaration, string manipulation, and control structures. It also covers SQL basics, including Data Definition Language (DDL) and Data Manipulation Language (DML), with examples of SQL statements for creating, altering, and deleting tables, as well as querying data. Additionally, it discusses accessing multiple tables and creating calculated values in SQL.

Uploaded by

paulas2014
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Free Visual Basic .

NET Course

VB NET Exercise Answers


Exercise A (Button code not shown)

Dim number1 As Integer


Dim number2 As Integer
Dim number3 As Integer = 10
Dim answer As Integer

number1 = 3
number2 = 5

answer = number1 + number2

answer = answer * number3

Textbox1.Text = answer

Exercise B

Dim FirstName As String


Dim LastName As String
Dim FullName As String

FirstName ="Bill"
LastName = "Gates"

FullName = LastName & " " & FirstName

Textbox1.Text = FullName

Exercise C
Dim FirstName As String
Dim MiddleName As String
Dim LastName As String
Dim FullName As String

FirstName ="Bill"
MiddleName = "Henry"
LastName = "Gates"

FullName = FirstName & " " & MiddleName & " " & LastName

Textbox1.Text = FullName

Exercise D

Dim FirstName As String


Dim LastName As String
Dim WholeName As String

FirstName = txtFirstName.Text
LastName = txtLastName.Text

WholeName = FirstName & " " & LastName

txtWholeName.Text = WholeName

Exercise E

Dim ButtonContents As String


ButtonContents = Button1.Text

txtVariables.Text = ButtonContents

Exercise G

Dim agerange As Integer

agerange = Val(textbox1.Text)

Select Case agerange


Case 13 To 19

MessageBox.Show( “In your Teens”)

Case 20 To 29

MessageBox.Show(“In your Twenties”)

Case 30 To 39

MessageBox.Show(“In Thirties ”)

Case Else

MessageBox.Show(“Not at a teen and over 39”)

End Select

Section 3, Part One

Dim number_in_textbox As Integer

number_in_textbox = Val(TextBox1.Text)

If number_in_textbox > 10 And number_in_textbox < 20 Then

MessageBox.Show("Number entered was: " & number_in_textbox)

Else

MessageBox.Show("Number entered was not between 10 and 20")


TextBox1.Text = ""

End If

Section 3, Part Two

Item One, Item Two, Item Three below can be replaced by whatever items you have in your
Combo Box list.

Dim MyVariable As String

MyVariable = ComboBox1.Text
Select Case MyVariable

Case "Item One"

MessageBox.Show("You like " & MyVariable & ", I see - good choice")

Case "Item Two"

MessageBox.Show("Really? " & MyVariable & "?")

Case "Item Three"

MessageBox.Show(MyVariable & "? Now you're just being silly!")

End Select

Exercise H

Dim startNumber As Integer


Dim endNumber As Integer
Dim i As Integer
Dim answer As Integer

startNumber = Val(TextBox1.Text)
endNumber = Val(TextBox2.Text)

If startNumber = 0 Or endNumber = 0 Then

MessageBox.Show("Empty textbox")
Exit Sub

End If

For i = startNumber To endNumber

answer = answer + i

Next i

MessageBox.Show(answer)

Exercise I
Dim message As String = ""
Dim counter As Integer = 0

If CheckBox1.CheckState = CheckState.Checked Then

message = message & CheckBox1.Text & vbNewLine


counter = counter + 1

End If

If CheckBox2.CheckState = CheckState.Checked Then

message = message & CheckBox2.Text & vbNewLine


counter = counter + 1

End If

If CheckBox3.CheckState = CheckState.Checked Then

message = message & CheckBox3.Text & vbNewLine


counter = counter + 1

End If

If CheckBox4.CheckState = CheckState.Checked Then

message = message & CheckBox4.Text & vbNewLine


counter = counter + 1

End If

If CheckBox5.CheckState = CheckState.Checked Then

message = message & CheckBox5.Text & vbNewLine


counter = counter + 1

End If

MessageBox.Show("You have chosen " & vbNewLine & message)

Select Case counter

Case 0

MessageBox.Show("You obviously don’t watch soaps!")


Case 1

MessageBox.Show("only 1 show watched")

Case 2

MessageBox.Show("2 shows watched")

Case 3

MessageBox.Show("3 shows watched")

Case 4

MessageBox.Show("4 shows watched")

Case 5

MessageBox.Show("a soap addict")

End Select

Exercise J

Tricky one, this. The solution is to change this line:

letter = strText.Substring(1)

to this:

letter = strText.Substring(i)

By using the loop variable i you advanced the counter for Substring.

Exercise K

Dim OneCharacter As Char


Dim FirstName As String
Dim i As Integer
Dim TextLength As Integer
FirstName = txtChars.Text
TextLength = FirstName.Length

For i = 0 To TextLength - 1

OneCharacter = FirstName.Chars(i)

If IsNumeric(OneCharacter) Then

MessageBox.Show("Number Found - Exiting")


Exit Sub

End If

Next

Exercise L

Dim OneCharacter As Char


Dim FirstName As String
Dim i As Integer
Dim TextLength As Integer
Dim numbercount As Integer = 0

FirstName = txtChars.Text
TextLength = FirstName.Length

For i = 0 To TextLength - 1

OneCharacter = FirstName.Chars(i)

If IsNumeric(OneCharacter) Then

numbercount = numbercount + 1

End If

Next

MessageBox.Show("found " & numbercount & " numbers")

Exercise M
Checking for a valid email address is quite tricky. In the code below, the Sub is just checking if
the email address has an @ sign. Notice that the Sub uses two paramaters, one to pass in the
email address and one to pass in the @ sign. You can then reuse this code to pass in, say, an
email address and the characters ".com"

'===================================
' BUTTON CODE
'===================================
Dim email As String
Dim chars_to_check As Char

email = txtEmail.Text
chars_to_check = "@"

TestEmail1(email, chars_to_check)

'===================================
' SUBROUTINE
'===================================
Private Sub TestEmail1( eMail As String, CheckChars As String)

Dim position As Integer

position = InStr(eMail, CheckChars)

If position = 0 Then

MessageBox.Show("Not a Valid email address")

End If

End Sub

Exercise N

Private Sub TextBox1_Leave( sender As Object, e As EventArgs) Handles TextBox1.Leave

Dim CheckTextBox As String

CheckTextBox = Trim(TextBox1.Text)
CheckTextBox = StrConv(CheckTextBox, VbStrConv.ProperCase)
TextBox1.Text = CheckTextBox

End Sub
Exercise O

Here are the Set and Get properties that change the height and width. (As was mentioned in the
text, however, the name of the Class (ConvertPostcode) is not a very good name for what this
does - changing the height and width of an image! Plus, picture boxes already have a height and
width property)

Private intHeight As Integer


Private intWidth As Integer

Public Property ChangeHeight() As Integer

Get

Return intHeight

End Get

Set( HeightValue As Integer)

intHeight = HeightValue

End Set

End Property

Public Property ChangeWidth() As Integer

Get

Return intWidth

End Get

Set( WidthValue As Integer)

intWidth = WidthValue

End Set

End Property

And here is the code for the button that uses the two properties:
Dim objAlterPicPox As ConvertPostcode
Dim NewHeight As Integer
Dim NewWidth As Integer

objAlterPicPox = New ConvertPostcode

objAlterPicPox.ChangeHeight = Val(txtHeight.Text)
NewHeight = objAlterPicPox.ChangeHeight
PictureBox1.Height = NewHeight

objAlterPicPox.ChangeWidth = Val(txtWidth.Text)
NewWidth = objAlterPicPox.ChangeWidth
PictureBox1.Width = NewWidth

objAlterPicPox = Nothing

Join Date
Sep 2006
Location
WindowFromPoint
Posts
4,081

Re: sorting an array into alphabetical order


You could probably just use the Array.Sort and Array.Reverse methods...

Code:

Dim student(5) As String


student(0) = "Jamal"
student(1) = "Ali"
student(2) = "Salim"
student(3) = "Mohammed"
student(4) = "Suliman"
student(5) = "Rashid"

Array.Sort(student) ' sort (A-Z)


Array.Reverse(student) ' reverse array
ListBox1.Items.AddRange(student) ' add to listbox

ii .Net Framework Class Library (FCL)

This is also called as Base Class Library and it is common for all types of applications i.e.
the way you access the Library Classes and Methods in VB.NET will be the same in C#,
and it is common for all other languages in .NET.
The following are different types of applications that can make use of .net class library.

1. Windows Application.
2. Console Application
3. Web Application.
4. XML Web Services.
5. Windows Services.

 In short, developers just need to import the BCL in their language code and use its
predefined methods and properties to implement common and complex functions like
reading and writing to file, graphic rendering, database interaction, and XML document
manipulation.

2a. DESCRIBING A VARIABLE

a variable is a storage area of the computer's memory. It is a temporary location in memory used
to hold data.

b. HOW TO DECLARE A VARIABLE

 First, we start with the Dim word, indicating to Visual Basic that we want to set up a
variable
 Then we give the variable a name (number1)
 Next, we "tell" VB that what is going inside the variable is a number (As Integer)
 Two more variable are set up in the same way, number2 and answer
 Dim number1 As Integer
Dim number2 As Integer
Dim answer As Integer

c. RULES FOR NAMING VARIABLES

 They must not use reserved words.


 They cannot start with a punctuation marks space or numbers (digit).
 Variables can contain digits but they cannot start with them.
 Variables are not case sensitive.

d. INITIALIZING A VARIABLE

 Giving a start value to a variable you use an equal sign


 For example

7.11 Introduction To SQL


The Structured Query Language (SQL) is used to interact with a database and access and edit
data in it. SQL statements are divided, according to their nature, into two parts- Data Definition
Language (DDL) and Data Manipulation Language (DML).

To perform an operation, SQL requires only few lines of code compared to other languages. SQL
statements include select which is used to access fields, tables and range of records in a database,
inserts for adding new data, and deletes for removing data. When a query is processed the result
will be returned in a Recordset.

7.11.1 DDL (Data Definition Language)

Data Definition Language is the language used to define the organization and storage of data.
Some of the DDL statements are,

CREATE TABLE Statement

The Create Table statement is used for creating a table with the given table name and field types.

Syntax
CREATE TABLE tablename (field1 type [(size)] [NOT NULL] [index1] [, field2
type [(size)] [NOT NULL] [index2] [, ...]] [, CONSTRAINT constraintname
[, ...]]) ;
Example
Create table tabStudent
(varStud_id Varchar2(12) NOT NULL,
varLast_Name Varchar2(12) NULL,
varFirst_Name Varchar2(30) NOT NULL,
varSS_No Varchar2(12) NOT NULL );

This statement will create a table with name tabStudent with the fields
varStud_id, varLast_Name, varFirst_Name and varSS_No, in which the field
varLast_Name can be NULL.
ALTER TABLE Statement
The Alter Table statement is used for adding a new column to existing
database or changing the width of an existing column and specifying a
default value for an existing column.
Syntax
ALTER TABLE tablename {ADD {COLUMN field type[(size)] [NOT NULL]
[CONSTRAINT index] [CONSTRAINT multifieldindex} ] ;
Example
ALTER TABLE tabStudent MODIFY (varStud_id Varchar2(12) NOT NULL);
DROP TABLE statement
The Drop Table statement is used for deleting a table from the database.
Syntax
DROP {TABLE table | INDEX index ON table} ;
Example
DROP tabStudent;
The arguments within square brackets are optional.

7.11.2 DML (Data Manipulation Language)

Data Manipulation Language is the language which is used to manipulate data in a database.

Some of the DML statements are,

SELECT statement

The SELECT statement is the most commonly used SQL statement. It is used to retrieve a group
of records from the database and place them in a recordset or dynaset for use by the application
program.

Syntax

SELECT fields FROM tablenames WHERE condition [sort option] [Group Option].

Example

The statement given below will retrieve all fields from the table, tabABC,

SELECT * from tabABC;


The asterisk (*) character stands for all the fields in that particular table. The
fields part of the Select instruction defines the fields included in the output
recordset. Any number of fields can be selected by specifying the names of
the fields in the SELECT statement. Calculated fields can also be selected
using the SELECT statement.

INSERT INTO statement

The Insert into statement is used to insert new records into a table.

Syntax
INSERT INTO tablename [(field1[, field2[, ...]])]
VALUES (value1[, value2[, ...])
Example
Insert Into tabStudent
(tabStud_id, varLast_Name, varFirst_Name, varSS_No)
values ('1001','Philip','George','X10101');
UPDATE statement
The Update statement updates the values in a table.
Syntax
UPDATE table
SET new value
WHERE criteria;
Example
Update tabStudent
Set varStud_id='1010'
where student_id=14;
DELETE FROM Statement
The Delete From statement removes the specified records from the database.
Syntax
Delete From table_name
[Where condition];
Example
Delete From tabStudent
where varStud_id='1010';

7.11.3 Accessing Multiple Tables

Typically, data will be stored in different tables after the Normalization


process covered in an earlier section. Normalization is done in order to
reduce duplicate data. The tables formed after normalization will be related
with each other. Related data can be retrieved using join operations within
an SQL statement. When data is to be retrieved from multiple tables, three
things should be known: knowledge about tables from which the data is to
be retrieved, the fields required and the relationship between the tables.

In some cases two tables will have fields with same name. In this case, the table name and a
period should be added with the field name within your SQL instruction in order to specifically
identify the field name. If you want to retrieve some fields in one table and all fields from
another, you can use the asterisk field selection character with the name of the second table only.
Each table used in the earlier part of the SQL instruction should be specified in the FROM clause
of the SELECT statement. Relationships between the tables is specified in the WHERE clause by
using a JOIN condition. The WHERE clause is used more often than the "JOIN" instruction in
SQL statements. The complete SQL statement is as follows:
SELECT tabEmp.[Firstname], tabEmp.[Lastname], tabDep.* FROM tabEmp, tabDep WHERE tabEmp.varDepid =
tabDep.varDepid;

In the above statement two tables are tabEmp and tabDep, related using the field, varDepid and the
relation is specified with the JOIN condition, tabEmp.varDepid = tabDep.varDepid. The result of the
query is the first and last name from tabEmp table and all related data from tabDep table are selected.

Creating Calculated Values


Calculation can be done on fields and can be used in the SQL statement for
further operations. A calculated field can be the result of an arithmetic
operation or the result of a string operation . In addition, there are many
operations and functions unique to the database. In SQL some arithmetic
functions are available to you such as sum(), avg(), min() ,max(). The
following SQL statement shows how to get the average age of employees in
the tabEmp table:
SELECT varName,avg(intAge) FROM tabEmp;
In the resulting recordset the calculated fields will be read only.
Alias Name for Tables
Some tables will have long names, which will make SQL statements, more
complex. You can assign a short name to any table instead of the large name
and then use the short name in the statements. By using aliases in the FROM
clause, you can assign a name to each table that makes sense to you.
For example, the alias name "e" can be given for the table tabEmp.

Controlling the Data


SQL can control the range of records to be processed by specifying the filter condition. The filter
conditions are specified in the WHERE clause. The syntax of the WHERE clause is,

WHERE condition
In the condition there are different logical statements. The various types of
logical statements are,

Comparison - used to compare a field to another field or a given value

(Example: (ftSalary) >10000)


LIKE - compares a field to a specified match pattern.
IN - A list of acceptable values is compared with a field. It checks whether a particular field value is in
the given set of values. (For example, State IN (" NY" ," NJ"," CT" ).

BETWEEN - Used to specify the value within a range.


The predicates LIKE, IN, BETWEEN have lot of options. In the WHERE clause multiple
conditions can be specified to filter more than one field at a time.

ORDER BY CLAUSE - Clauses can be used to specify the records that are retrieved be sorted in a specific
order. ORDER BY CLAUSE can be used for this purpose in the SELECT statement to get the rows in the
recordset in a specific order. The records in a dynaset can be sorted using the SORT order in the ORDER
BY clause. Multiple fields can be specified in the SORT method.

Example:
SELECT * FROM tabEmp ORDER BY intAge, varName Desc;

The above query will select the records in descending order with respect to intAge and varName
from the table tabEmp.

 Select Operation (σ)


 It selects tuples that satisfy the given predicate from a relation.
 Notation − σp(r)
 σ condition relation
 Example
 Collage admission database with the following tables
 Collage(cname, State , enrolment)
 Student(sID ,cname, GPS, sizeHS)
 Apply(sID,sname, major, decision)
 SELECT is used to obtain a subset of the tuples of a relation that satisfy a select
condition.
 For example, find all students born after 1st Jan 1980:
 SELECTdob '01/JAN/1980'(students)
 Students with GPA > 3.7
 σ GPA> 3.7 student
 Students with GPA>3.7 and HS<1000
 σ GPA> 3.7 ^ HS<1000student
 Application for Stanford CS major
 σ cname=‘Stanford ’^ major = CS Apply

It projects column(s) that


satisfy a given predicate.

 Notation − ∏A1, A2, An (r)


 Where A1, A2 , An are attribute names of relation r.
 Duplicate rows are automatically eliminated, as relation is a set
 Example
 ∏Sid,decision Apply
 SELECT and PROJECT can be combined together. For example, to get ID and name of
students with GPA > 3.7
 ∏Sid,Sname (σGPA>3.7 students)
 Combines information of two different relations into one.
 Notation − r Χ s

 Consider two relations R and S.

 UNION of R and S
the union of two relations is a relation that includes all the tuples that are either in R or in S or in
both R and S. Duplicate tuples are eliminated.

 INTERSECTION of R and S
the intersection of R and S is a relation that includes all tuples that are both in R and S.

 DIFFERENCE of R and S
the difference of R and S is the relation that contains all the tuples that are in R but that are not
in S.

 For set operations to function correctly the relations R and S must be union compatible. Two
relations are union compatible if

 they have the same number of attributes

 the domain of each attribute in column order is the same in both R and S.

UNION Example
INTERSECTION Example

DIFFERENCE Example

The Cartesian Product is also an operator which works on two sets. It is sometimes called the CROSS
PRODUCT or CROSS JOIN.

 It combines the tuples of one relation with all the tuples of the other relation.
CARTESIAN PRODUCT example

JOIN Example

You might also like