Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

CICS 314: Advanced Visual Basic

.NET Programming

Multiple Tables and Parameterized Queries

- Tutorial 4 – SQL Server Database

Ghana Communication Technology University


Lecturer – Dr. Forgor Lempogo
2024
Objectives

❑By the end of this Lesson, students should be able to:


❑Understand how to work with multiple related data tables /
master/detail DataSets
❑Add and configure columns to a DataGridView
❑Know how to pass data between forms
❑Understand how to Work with parameterized queries
❑Create and use dataBinding source, including its methods and
properties
❑Understand how to bound different controls to a binding source
2
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
Parameterized Queries
❑The SQL SELECT statements used so far have
been without the WHERE clauses.

❑In a SELECT statement, the WHERE clause can


be used to limit the results returned.

❑For example, to display the names of a student


with a specific student ID, we could use the
following query:
SELECT studentID, name FROM Students WHERE studentID = “01”

SELECT studentID, name FROM Students WHERE name = “Kwaku”

3
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
Parameterized Queries

❑Typically, the values used in a WHERE clause are


determine by some external source, such as:
❑Querystring Value
❑Session Variable
❑ User input from a web control on the page
❑Etc.

❑Ideally, such inputs are specified through the use of


parameters.

4
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
Parameterized Queries - SQL Server
❑With Microsoft SQL Server, parameters are
denoted using @parameterName
❑Thus, SQL server uses Named Parameters

❑For example, to display the names of a student


with a specific student ID, we could use the
following query:

SELECT studentID, name FROM Students WHERE studentID = @student_ID

SELECT studentID, name FROM Students WHERE name = @studentName

5
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
Parameterized Queries - SQL Server
❑The SqlDataSource supports parameterized
queries, both for SELECT statements and
INSERT, UPDATE, and DELETE statements.
❑Parameter values can be automatically pulled
from a variety of sources and can be assigned
programmatically.
❑In this tutorial, we'll see how to define
parameterized queries as well as how to specify
the parameter values.

6
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
Parameterized Queries - OLEDB
❑ With OleDb, Parameters are recognized by their
position, not by their name.

❑ Thus, OLEDB uses Unnamed Parameters

❑ Instead of naming the parameters, question marks


are used.

❑ For example, to display the names of a student with


a specific student ID and name, we could use the
following query:
SELECT studentID, name FROM Students WHERE studentID = ?

SELECT studentID, name FROM Students WHERE name = ?


7
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
Parameterized Queries - OLEDB
❑ Consequently, it is vital to ensure that parameters
are added to the collection in the order they appear
in the SQL, otherwise a "Too few parameters"
exception could occur.

❑ At the very least, your values will get inserted into


the wrong fields, or nothing happens at all.

❑ For the sake of code readability,


AddWithValues(string, object) can take a non-empty
string giving a name to the parameter, although an
empty string ("") will do.

8
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
Parameterized Queries - OLEDB
❑ Compose the query, replacing the values you want to be
parameters with question marks.

❑ Use the query to build a command object.

❑ Use the command's Parameters. AddWithValue method to add


parameter objects to the command.

❑ The database will replace the question marks with the parameters
in the order in which they are added.

❑ In other words, the first question mark is replaced with the first
parameter, and so forth.

❑ Execute the command and process the results as usual.


9
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
Parameterized Queries
❑ For both SQL Server and OLEDB Databases, after creating the SQL
Query, values for the parameter must be processed

❑ Thus, where must the value of the parameter come from?

❑ Use the query to build a command object.

❑ Use the command's Parameters. AddWithValue method to add


parameter objects to the command.

❑ For OLEDB the database will replace the question marks with the
parameters in the order in which they are added.

❑ In other words, the first question mark is replaced with the first parameter,
and so forth.


10 Execute the command and process the results as usual.
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
Parameterized Queries - EXAMPLES
❑ Example SQL Server
Dim student_ID As String = txtStudentID.Text
idSQL= “SELECT studentID, name FROM Students WHERE studentID = @studentID”
Dim cmd As New SQLCommand(idSQL, con)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue(“@studentID", student_ID)
con.Open()
cmd.ExecuteNonQuery()
da.SelectCommand = cmd
da.Fill(ds, “studentTable")

❑ Example OLEDB
Dim student_ID As String = txtStudentID.Text
idSQL= “SELECT studentID, name FROM Students WHERE studentID = ?”
Dim cmd As New OleDb.OleDbCommand(idSQL, con)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue(“studentID", student_ID)
con.Open()
cmd.ExecuteNonQuery()
da.SelectCommand = cmd
11 da.Fill(ds, “studentTable")
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
Getting Started

❑Open Last weeks Windows application in


Visual Studio

❑Add the windows forms

❑Design the user interfaces

❑Write the code

12
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
Results of Last weeks Project

13
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
Modify Last weeks Form
❑ Modify Last weeks form1
by adding one (1) Menu
(ToolStripMenuItem) item
namely VIEW

❑ Under the menu Item


VIEW, Add three (3) sub
menu items namely
❑ MESSAGES
❑ CALLS
❑ ALL CONTACTS

❑ For this lesson, only the


MESSAGES Menu item will
be used to display the new
form to be created

❑ The rest (CALLS AND ALL


CONTACTS) will be used
later

14
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
The Message Reader Function

❑ To try our hands on parameterize queries, we will create a


message reader function for the contact manager App

❑From the main window (last weeks form) the user should be
able to Navigate to or Search for a contact.

❑Select a specific contact to view all messages sent by that


contact

❑Select a specific message from the list of message to read.

❑The Person_TB and Message_TB tables will be used for


this

15
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
Add and Design New Form
❑ Add a new form to your
project and give it an
appropriate name (mine is
frmViewContactMessages
)

❑ Add the following controls


and reorganize as follows
(you may copy the controls
in the CONTACT
INFORMATION GroupBox)

❑ Beneath that are a


Groupbox and a
DataGridView

❑ This form will be used to display information on a selected


16 contact as well as all messages sent by that contact
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
MessagesToolStripMenuItem_Click

❑ The click event of the MESSAGES menu item under VIEW will be
used to lunch the new form (frmViewContactMessages)

❑ The code is as follows:

Dim Person_ID As String = txtID.Text


‘txtID is the textbox that contains the ID of the selected contact
Dim messageForm As New frmViewContactMessages
messageForm.Tag = Person_ID
messageForm.ShowDialog()

17
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
Declaring Public Variables – SQL Server

Imports System.Data.SqlClient

Public Class frmViewContactMessages


Dim con As New SqlConnection
Dim ds As New DataSet
Dim da As New SqlDataAdapter
Dim personSQL As String
Dim messageSQL As String
Dim conString As String
Dim inc As Integer
18
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
frmViewContactMessages Form LOAD
Event- SQL Server (1/2)
conString = "Data Source=(localdb)\ProjectsV12;Initial
Catalog=Contact_DB"
con.ConnectionString = conString
‘used to store the ID of the selected contact passed from Form1
Dim Person_ID As String
Person_ID = Me.Tag.ToString
‘the parameterize query to fetch data on the selected contact
Dim personSQL As String = "select * from Person_TB where
P_ID=@P_ID"
Dim cmdPerson As New SqlCommand(personSQL, con)
cmdPerson.CommandType = CommandType.Text ‘Creating the
parameter and passing the value of the selected ID
cmdPerson.Parameters.AddWithValue("@P_ID", Person_ID)
con.Open()
cmdPerson.ExecuteNonQuery()
da.SelectCommand = cmdPerson
da.Fill(ds, "selectedPerson")
19
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
frmViewContactMessages Form LOAD
Event- SQL Server – (2/2)

‘the parameterize query to fetch data on the messages sent by the selected contact
Dim messageSQL As String = "select * from Message_TB where Sender_ID=@Sender_ID"
Dim cmdMessage As New SqlCommand(messageSQL, con)
cmdMessage.CommandType = CommandType.Text
‘Creating the parameter and passing the value of the selected ID
cmdMessage.Parameters.AddWithValue("@Sender_ID", Person_ID)
cmdMessage.ExecuteNonQuery()
da.SelectCommand = cmdMessage
da.Fill(ds, "selectedPersonMessages")
con.Close()
showData()

20
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
The showData() Method
Private Sub showData()
txtID.Text = ds.Tables("selectedPerson").Rows(inc).Item(0)
txtFName.Text = ds.Tables("selectedPerson").Rows(inc).Item(1)
txtLName.Text = ds.Tables("selectedPerson").Rows(inc).Item(2)
cmbGender.Text = ds.Tables("selectedPerson").Rows(inc).Item(3)
dtpDateOfBirth.Value = ds.Tables("selectedPerson").Rows(inc).Item(4)
txteMail.Text = ds.Tables("selectedPerson").Rows(inc).Item(5)
txtPhone.Text = ds.Tables("selectedPerson").Rows(inc).Item(6)
txtAddress.Text = ds.Tables("selectedPerson").Rows(inc).Item(7)
txtDetails.Text = ds.Tables("selectedPerson").Rows(inc).Item(8)
‘link (bound) the Datagridview control to the selectedPersonMessages in the ds dataset
dgvMessages.DataSource = ds.Tables("selectedPersonMessages")
‘Display the inserted (ViewMessage) column as the last column in the datagridview
dgvMessages.Columns("ViewMessage").DisplayIndex = 4
End Sub

21
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
Adding a Column to DataGridview

❑ Make sure the


DataGridView is
selected

❑ Click on the little


arrow on the top-
left corner of the
datagridview and
choose Add
Column to lunch
the Add Column
Window

22
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
Adding a Column to DataGridview
❑ In the Add Column window choose Unbound column
❑ Type an appropriate name in the name field (must be a valid
identifier) – mine is ViewMessage
❑ Select DataGridViewButtonColumn from the type dropdown
❑ Type an appropriate Text in the Header text field
❑ Select Add to add the column (click Add only once and select
cancel to close the window)

23
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
Adding a Column to DataGridview
❑ Go back to the DataGridView and Click on the little arrow on the
top-left corner and choose Edit Column
❑ In the Edit Column window you will notice properties on the right
side.
❑ Change the TEXT property to something appropriate (eg. View
Message)
❑ Change the UseColumnTextForButtonValue property to TRUE
❑ The click OK to finish.

24
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
View Message – CellContentClick
❑ Double-click anywhere on the dataGridView to enter
the CellContentClick and type the ff. code.

If e.ColumnIndex = 0 Then
' ViewMessage button clicked
' Get the ID of the selected Message
Dim i As Integer = e.RowIndex
Dim row As DataGridViewRow = dgvMessages.Rows(i)
Dim cell As DataGridViewCell = row.Cells(1)
Dim MessageID As String = cell.Value
' Display the ViewMeassage form
Dim messageForm As New frmViewMeassage
messageForm.Tag = MessageID
messageForm.ShowDialog()
End If
25
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
Add and Design New Form
- frmViewMeassage
❑ Add a new form to your
project and give it an
appropriate name (mine is
frmViewMeassage)

❑ Add the following controls


and reorganize as follows

❑ 4 textboxes, 4 labels and 1


button

❑ This form will be used to display information on a selected Message, when the
ViewMassage button is selected by the user on the frmViewContactMessages
26 Form
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
Declaring Public Variables – SQL Server
- frmViewMeassage
Imports System.Data.SqlClient

Public Class frmViewContactMessages


Dim con As New SqlConnection
Dim ds As New DataSet
Dim da As New SqlDataAdapter
Dim personSQL As String
Dim messageSQL As String
Dim conString As String
Dim inc As Integer
27
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
frmViewMeassage Form LOAD Event-
SQL Server
conString = "Data Source=(localdb)\ProjectsV12;Initial Catalog=Contact_DB"
con.ConnectionString = conString
Dim Message_ID As String
Message_ID = Me.Tag.ToString
con.Close()
Dim messageSQL As String = "select * from Message_TB where M_ID=@M_ID"
Dim cmdMessage As New SqlCommand(messageSQL, con)
cmdMessage.CommandType = CommandType.Text
cmdMessage.Parameters.AddWithValue("@M_ID", Message_ID)
con.Open()
cmdMessage.ExecuteNonQuery()
da.SelectCommand = cmdMessage
da.Fill(ds, "selectedMessage")
con.Close()
displayMessage()

28
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
The displayMessage() Method

Private Sub displayMessage()


txtMID.Text = ds.Tables("selectedMessage").Rows(inc).Item(0)
txtSender.Text = ds.Tables("selectedMessage").Rows(inc).Item(1)
txtSentDate.Text = ds.Tables("selectedMessage").Rows(inc).Item(2)
txtContent.Text = ds.Tables("selectedMessage").Rows(inc).Item(3)
End Sub

29
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
Announcement
❑ Due to the STRIKE AND THE SUBSEQUENT EXTENTION
OF THE SEMESTER FOR 2 WEEKS, the DEADLINE for the
APPROVAL OF TOPIC AND submission of the semesters
Project work has been extended.
❑ The DEADLINE for the APPROVAL OF TOPIC IS:
❑ FRIDAY 3RD SEPTEMBER 2021

❑ The DEADLINE for the submission of the COMPLETED


Project IS:
❑ FRIDAY 17TH SEPTEMBER 2021

❑ This Implies
❑ All other submission rules remain the same
❑ From NEXT WEEK to the deadline, you can submit your project
ON THE COURSE PAGE AND via e-mail.
❑ This extension means, you might not get the results before the
31 end of lectures.
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery
Any Questions?

39
CICS 314: Advanced Visual Basic .NET Programming - GCTU 2022 Delivery

You might also like