Tải bản đầy đủ (.pdf) (50 trang)

Tài liệu Programming Microsoft SQL Server 2000 with Microsoft Visual Basic .Net - P7 ppt

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (863.09 KB, 50 trang )

labels visible by passing the argum ent True t o ShowLabelsBoxes. As a resu lt , a
user can ent er a SQL Server login and password so t hat t he form can at tem pt t o
m ake a connection based on a SQL Server instead of a Windows login.
Finally, by click ing the Windows NT radio but ton, the user invok es t he
RadioButt on1_CheckedChanged event pr ocedure. This procedure m akes t he
cont r ols for SQL Server login credent ials invisible if t hey are show ing. When t he
user clicks t his RadioBut t on1, it indicat es he or she want s t o make a connection
wit h a Windows login. Therefore, Form 3 doesn’t need to show t he contr ols for a
SQL Server login.
Private Sub Form3_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load

’Set RadioButton1 to Checked for connection via
’Windows NT login.
RadioButton1.Checked = True

’Hide login and password controls because they
’aren’t necessary with Windows NT login.
ShowLabelsBoxes(False)

End Sub

Private Sub RadioButton1_CheckedChanged _
(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles RadioButton1.CheckedChanged

’Hide login and password controls because they
’aren’t necessary with Windows NT login.
ShowLabelsBoxes(False)


End Sub

Private Sub RadioButton2_CheckedChanged _
(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles RadioButton2.CheckedChanged

’Show login and password controls because they
’are necessary for a SQL Server login.
ShowLabelsBoxes(True)

End Sub

Sub ShowLabelsBoxes(ByVal bolShowEm As Boolean)

’Set the visibility of the second and third text
’boxes and their labels according to the value
’of bolShowEm.
Label2.Visible = bolShowEm
TextBox2.Visible = bolShowEm
Label3.Visible = bolShowEm
TextBox3.Visible = bolShowEm

End Sub

The following excerpt from t he Form 3 m odule shows the code devot ed to m aking
the connect ion based on t he radio button selection and t ext box ent ries. The
excerpt st art s wit h a m odule- level declaration of t he cnn1 obj ect reference as a
SqlConnect ion obj ect . A m odule- level declarat ion isn’t st rict ly necessary in the
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

cont ext of this sam ple, but t his type of declarat ion m akes t he SqlConnect ion
obj ect available t o ot her procedures t hat could use it . I n any event , not ice t hat
the declarat ion specifies t he full nam e for t he nam espace cont aining the
SqlConnect ion obj ect reference. This is because the m odule doesn’t include an
I m ports st at em ent for t he Syst em .Data.SqlClient nam espace. By not using t he
I m ports st at em ent at t he top of t he For m 3 module, the Catch clause in the
excerpt m ust reference a Syst em except ion instead of the m ore specific SqlClient
except ion. I n spit e of this deviat ion from the sam ple in t he “Cat ching
SqlConnect ion Except ions” sect ion, SqlClient ex cept ions st ill percolat e up through
the m ore general Sy st em except ion specificat ion.
Aside from the declarat ion issues for cnn1, the balance of t he code excerpt is a
st raightforward m ixt ure of t he code sam ples developed previously in this chapter.
Based on whet her RadioButton1 is checked, t he But t on1_Click event procedure
com poses a connection string for eit her a Windows or a SQL Server login. Then
the procedure inst ant iates a connect ion based on t he connect ion st ring. Wit hin a
Try…Catch…Finally st at em ent , t he procedure at t em pts t o open t he connect ion. I f
the attem pt succeeds, t he procedur e displays a m essage confirm ing t he at t em pt
was successful and nam ing the database. Ot her wise, cont rol flows t o t he Cat ch
clause, and t he procedure displays t he error m essage associat ed wit h t he
except ion. Because SqlClient except ions percolate up through t he Syst em
except ion, t he m essage is likely t o be specific and helpful for diagnosing any
problem s.
‘Using the full namespace name removes the need to
‘start module with Imports System.Data.SqlClient.
Dim cnn1 As System.Data.SqlClient.SqlConnection

Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click

’Make local variable declarations.

Dim strDBName As String = TextBox1.Text
Dim strConnect As String

’Compose a connection string for either a Windows
’or a SQL Server login.
If RadioButton1.Checked = True Then
strConnect = “Data Source=(local);” & _
“Initial Catalog=“ & strDBName & _
“;Integrated Security=SSPI"
Else
Dim strLogin As String = TextBox2.Text
Dim strPassword As String = TextBox3.Text
strConnect = “Data Source=(local);” & _
“Initial Catalog=“ & strDBName & “;” & _
“user id=“ & strLogin & _
“; password=“ & strPassword
End If

’Instantiate a SqlConnection object based on the
’connection string.
cnn1 = _
New System.Data.SqlClient.SqlConnection(strConnect)

’Embed the attempt to open the cnn1 object inside a
’Try...Catch...Finally statement, and display a
’message for the exception if there is one.
Try
cnn1.Open()
MsgBox(“Successfully connected to “ & cnn1.Database & _
“ database on local server.”)

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Catch er As System.Exception
MsgBox(er.Message)
End Try

End Sub


W or kin g w ith Com m a nd and Da taRea der Obj ect s
One of the m ost com m on uses for Com m and obj ect s is to contain t he SQL st ring
that defines t he values cont ained in a Dat aReader object . Therefore, this sect ion
drills down on t hat use for Com m and obj ect s. I n this sect ion, you learn how to
form at the display of values in a DataReader obj ect as well as how t o populat e a
Dat aReader wit h either a SQL st ring or a stored procedure. Beyond t hese typical
applicat ions for Com m and obj ect s with Dat aReader obj ect s, the sect ion also
includes a sam ple t hat dem onst rat es how to use t he Com m and obj ect for dat a
definit ion task s, such as creating a user- defined funct ion. Th e present ation of t he
topic covers a special m et hod for Com m and obj ect s t hat is appropriat e when t he
Com m andText propert y for a Com m and obj ect doesn ’t ret urn any values.
Displaying Result s in a M essage Box or t he Ou tput W indow
I t ’s easy t o put SqlCom m and and SqlDataReader obj ect s t o use for report ing
results from a SQL Ser ver database. St art by connect ing to t he rem ot e dat a
source from which you want t o display result s. Next declare a Com m and obj ect as
a SqlCom m and type. The Com m and obj ect requires two input s: a dat abase
connect ion and a source of SQL st atem ents t o ex ecut e. You can link a Com m and
obj ect t o a Connect ion obj ect when you instant iate t he Com m and object . Specify
a data source for t he Comm and obj ect to return wit h either a SQL st ring or a
st ored procedure. This capabilit y of com m ands t o take SQL st at em ent s and
st ored procedures allows you to draw on all dat a access t opics covered in
Chapters 3 t hrough 5.

Dat aReader object s read t he result set returned by Com m and obj ect s. Use the
ExecuteReader m et hod on a Com m and obj ect t o convey it s r esult set to a
Dat aReader object . After the invocat ion of the Execut eReader m et hod, you can
ext ract sequent ial rows from a result set wit h the Read m et hod for the Dat a-
Reader obj ect. Use one of t he Dat aReader Get m ethods t o ext ract the value for a
specific colum n int o a data t ype designated by t he Get m et hod. Colum ns are
designated wit h index num bers of 0 t hrough 1 less t han t he number of colum ns
in a result set.
The Enum erat eCategories procedure, w hich appears next, dem onst rat es t he
applicat ion of t hese guidelines for using Com m and and DataReader object s. You
can inv ok e this pr ocedure fr om Module1 in t he My ADODOTNETSam ples solut ion
by adapting t he inst ruct ions for running ot her procedur es from Module1. The
procedure enum erat es Cat egoryI D and CategoryNam e values from t he Cat egories
table in t he Nort hw ind dat abase. A com piler const ant , bolOut putWindow , perm its
you t o direct the content s of a Dat aReader obj ect to eit her a m essage box or the
Output window in the Visual St udio .NET design environm ent. The default value
for bolOut put Window direct s the DataReader contents t o a message box.
After assigning a v alue t o the com piler const ant, the Enum erat eCategories list ing
begins by declaring and inst ant iat ing cnn1 as a Connect ion obj ect befor e invoking
the object ’s Open m ethod. Next t he procedur e declares cm d1 as a Com m and
obj ect and specifies cnn1 as its Connect ion propert y wit h t he Creat eCom m and
m et hod for cn n1. The list ing proceeds t o assign a SQL st ring to t he Com m andText
propert y for cm d1. Wit h an ExecuteReader m et hod in a declarat ion for t he drd1
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Dat aReader, the procedure generat es a r esult set for drd1 based on t he SQL
st ring used to define cm d1.
N ote
Throughout this chapter , and elsewhere in t he book, I use
generic t erm s interchangeably when referencing specific
classes in t he Syst em .Data.SqlClient nam espace. For

example, I use the term DataReader to reference t he m ore
specific class nam e SqlDat aReader. Using the generic term
rem inds y ou t hat SqlClient classes hav e parallel classes in
ot her .NET data providers, nam ely t he OLE DB .NET data
provider and the ODBC .NET dat a provider.
After t he conclusion of t he ExecuteReader m et hod, t he Dat aReader obj ect is
ready t o expose it s contents t o a Visual Basic .NET applicat ion. The balance of t he
procedure int roduces you t o t wo different st rat egies for achiev ing this. A com piler
I f…Then…Else st atem ent based on a com piler const ant adds one of t wo
st atem ents t o t he com piled version of t he procedure. Either st at em ent ret urns a
row from t he DataReader obj ect , but t hey display the row in different ways.
Alt hough t he list ing sh ows bot h the Then and Else clauses, t he com piled
procedure contains only one or t he other clause based on the com piler const ant
value for bolOut putWindow. Before encountering t he com piler I f…Then…Else
st atem ent, the procedure declares a str ing constant that can serve as a t it le for
the enum erat ed values in a m essage box. The constant ends wit h a St r Dup
funct ion that can duplicate a st ring const ant any num ber of tim es. I n this case,
the funct ion appends t w o carriage ret urns t o t he end of the text for t he t it le. Th e
int rinsic constant , vbCr, denot es the st ring equivalent of a carr iage return.
Next t he procedure starts a Do…While st atem ent wit h the condit ion drd1.Read()
. This condit ion will ret urn t he value True as long as t here are rem aining rows in
the Dat aReader. After the Read m et hod passes t hrough all the rows from t he
drd1 obj ect, the condit ion returns the value False, which causes cont rol t o pass to
the first st at em ent aft er the Loop st at em ent for t he Do…While st at em ent . The
com piler I f…Th en…Else st atem ent com piles one of t w o possible st atem ents
depending on t he value of bolOut putWindow. When bolOut put Window equals its
default value ( False), the st at em ent appends Cat egoryI D and Cat egoryNam e
values for t he current row to a st ring value. The values for each row end wit h a
carriage return (vbCr) . I f bolOutput Window equals True, Visual Basic .NET
com piles a different st at em ent that sim ply echoes t he row values t o t he Out put

window w it h t he Wr it eLine m et hod for a Console obj ect . Notice t hat t he t wo
com piled st at em ents use slightly different techniques for capt uring t he first
colum n value for CategoryI D. Both stat em ents use a GetI nt32 m et hod because
the SQL Server dat a t ype of int for Cat egoryI D is consistent wit h t he .NET value
type of I nt32, a 32- bit signed int eger. However, the pat h for adding the values t o
a st ring for display in a m essage box invok es the ToSt ring m et hod to conv ert
explicit ly t he I nt 32 num ber t o a st ring. This kind of conversion is preferred
because it saves t he t im e for a run-t im e det erm inat ion of how to finally represent
a ret urned value.
Sub EnumerateCategories()
’Compiler constant directing output to Output window
’or a message box. Default value is False.
#Const bolOutputWindow = False

’Declare and open connection to Northwind.
Dim cnn1 As SqlConnection = New _
SqlConnection(“Data Source=(local);” & _
“Integrated Security=SSPI;Initial Catalog=northwind”)
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
cnn1.Open()

’Declare a command and assign a SQL string to it.
Dim cmd1 As SqlCommand = cnn1.CreateCommand()
cmd1.CommandText = _
“SELECT CategoryID, CategoryName FROM Categories"

’Declare a data reader and copy result set from SQL string
’for cmd1 to drd1.
Dim drd1 As SqlDataReader = cmd1.ExecuteReader()


’Loop through data reader and display in Output
’window or message box.
Dim str1 As String = _
“Summary of CategoryID and Category Names” _
& StrDup(2, vbCr)
Do While drd1.Read()
#If bolOutputWindow = True Then
Console.WriteLine(“Category “ & drd1.GetInt32(0) & _
“ is “ & drd1.GetString(1))
#Else
str1 = str1 & “Category “ & _
drd1.GetInt32(0).ToString & _
“ is “ & drd1.GetString(1) & vbCr
#End If
Loop

’Conditionally display results in a message box.
#If bolOutputWindow = False Then
MsgBox(str1)
#End If

’Close data reader and connection object references.
drd1.Close()
cnn1.Close()

End Sub

After control passes from the Do…While st atem ent , cont rol can flow opt ionally to
a MsgBox funct ion st atem ent for displaying t he st ring com put ed in t he loop. A
com piler I f…Th en stat em ent inserts t he MsgBox funct ion into t he com piled

procedure if bolOut put Window equals False. Figure 10- 5 shows t he outcom e from
the procedure when t he value of bolOutputWindow is False, and Figure 10-6 is an
excerpt from t he Output window generated when bolOutput Window is Tr ue. No
m att er w hich path t he procedure takes t o generat e resu lt s, it ends by closing the
drd1 and cnn1 obj ect references. You should always per form these t ask s when
you no longer need a Dat aReader obj ect so that SQL Server can m ake t he
connect ion available for ot her requirem ents.
Figur e 1 0 - 5 . Ret u rn for t h e Enu m e rat eCat e gories pr ocedu re w he n
bolOu t put W indow equ als Fa lse .
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

Figur e 1 0 - 6 . An ex cerp t from th e ret urn for th e Enum era t e Cat e gories
pr ocedur e w h en bolOu t pu t W indow equ als Tru e .

Displaying Row s in Blocks fr om a Dat aRea der
The preceding sam ple dem onst rat es how conv enient a m essage box can be for
display ing t he cont ents of a Dat aReader obj ect . However, a single m essage box
can be filled t o its charact er lim it before it com plet es displaying results from a
Dat aReader object . A workar ound t o t his situat ion is t o display your result s fr om
the Dat aReader obj ect s in blocks of x row s at a tim e. When your application
displays rows in blocks, users can sequentially page t hrough a resu lt set to find
an item , or it em s, of interest. Because the Dat aReader provides forw ard- only
data access, you cannot page back, but you can provide your users a forward-
only look at som e data.
The Enum erat eCust om erI DNam es procedure allows a user to sp ecify t he num ber
of row s t o sh ow in a m essage box. The procedure ret urns the Cust om erI D and
Com panyNam e colum n values from the Cust om ers t able in t he Nort hw ind
database. You can invoke t he Enum erat eCustom erI DNam es procedure fr om the
m ain procedure in Module1. Launching this procedure is slight ly differ ent t han
wit h preceding sam ples from Module1. I n t his case, you m ust pass along an

argum ent value as you invoke t he procedure. The argum ent is for t he m axim um
num ber of rows t o show in a t ext box. The result set fr om t he Com m and obj ect
for a Dat aReader object m ay ext end over sever al blocks and require m ultiple
m essage box es. Each m essage box , except the final one, m ust hold t he m axim um
num ber of rows per block passed as an argum ent t o the
Enum erateCust om erI DNam es procedur e. The final m essage box will display from
one row up t o t he m axim um num ber of rows.
The Enum erat eCust om erI DNam es procedure st arts in t he sam e general fashion
as t he preceding one in t hat it m akes a connect ion t o t he Northw ind dat abase and
then populates a DataReader, drd1, w ith the result s of a Com m and object, cm d1.
The sole dist inct ion in how t he tw o procedures st art is t hat t his one has a
different SQL st ring for the Com m and obj ect that ret urns m ore rows t han t he one
in the earlier sam ple. This larger num ber of r ows in t he Dat aReader for this
sam ple calls for special t reat m ent because a single m essage box cannot display
all its rows.
The balance of the procedure dem onst rat es one solut ion for the problem of too
m any rows t o display in a m essage box. Two code blocks facilitate t he solution.
The first block it erat es t hr ough the rows in drd1 in blocks of int Size. The
procedure obt ains a value for int Size as a passed argum ent from t he procedur e
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
that calls t he Enum erat eCust om erI DNam es pr ocedure. A user can specify a block
size t hat does fit within a single m essage box no m at t er how m any rows are in
the Dat aReader. By clicking OK on each m essage box, the user can view
successive blocks of rows from t he Dat aReader. The second code block captures
any rem aining rows at the end of a Dat aReader obj ect t hat don’t fill a com plet e
block .
The first code block uses int 1 as a variable t o count t he cum ulat ive num ber of
rows read from t he drd1 DataReader. A st ring variable, st r1, accum ulates rows in
successive blocks of size int Size. The first code block uses a Do…While st atem ent
wit h a condit ion of drd1.Read() t o pass successively t hrough all the rows in the

drd1 DataReader . As the code block reads each new row, it recom put es st r1 so
that t he new row appears at the bot t om of t he st ring variable. When t he
rem ainder of int 1 divided by int Size equals 0, the procedur e accum ulat es a new
block of rows ( of size int Size) t o display in a m essage box. The expression int1
mod intSize ret urns t he rem ainder of int1 divided by int Size. When the first
code block detect s t he end of a block of rows, t he st ring variable st oring row
values is passed to a MsgBox funct ion as t he m essage argum ent . Aft er printing
the m essage, t he procedure resets t he st ring variable st r1 t o st art a new block of
rows. Then t he whole process st arts over again.
When no m ore rows rem ain in the DataReader, the procedure passes cont r ol to
the second code block. This second block starts by test ing t o see whet her any
rows rem ain t hat didn’t appear since t he display of t he last m essage box. Any
rem ainder of int 1 divided by int Size signals undisplayed rows. I f there are any of
t hese r ow s, t he second code block passes t he value of st r1 to a MsgBox funct ion
as t he m essage argum ent t o show them . The pr ocedure concludes in t he
st andard way by closing t he Dat aReader object and its Connect ion obj ect .
Sub EnumerateCustomerIDNames(ByVal intSize As Integer)
’Declare and open connection to Northwind.
Dim cnn1 As SqlConnection = _
New SqlConnection(“Data Source=(local);” & _
“Integrated Security=SSPI;Initial Catalog=northwind”)
cnn1.Open()

’Declare command and assign a SQL string to it, and then
’declare a data reader and copy result set from cmd1 to drd1.
Dim cmd1 As SqlCommand = cnn1.CreateCommand()
cmd1.CommandText = _
“SELECT CustomerID, CompanyName FROM Customers"
Dim drd1 As SqlDataReader = cmd1.ExecuteReader()


’Loop through data reader in blocks of intSize and sequentially
’display the contents of successive blocks.
Dim int1 As New Integer()
Dim str1 As String = _
“CustomerID and matching CompanyName column values” _
& StrDup(2, vbCr)
Do While drd1.Read()
str1 = str1 & drd1.GetString(0) & vbTab & _
drd1.GetString(1) & vbCrLf
int1 += 1
If (int1 Mod intSize) = 0 Then
str1 = str1 & StrDup(2, vbCr) & _
“Click OK for next “ & _
intSize.ToString & “ customers."
MsgBox(str1, , “CustomerID and Customer Name”)
str1 = _
“CustomerID and matching CompanyName “ & _
“column values” & StrDup(2, vbCr)
End If
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Loop

’If a partial block remains at end of data reader contents,
’display partial block.
If (int1 Mod intSize) > 0 Then
str1 = str1 & StrDup(2, vbCr) _
& “Click OK to close message box."
MsgBox(str1, , “CustomerID and Customer Name”)
End If


’Close data reader and connection object references.
drd1.Close()
cnn1.Close()

End Sub

Figure 10- 7 show s t he first and last m essage boxes that resu lt from running the
Enum erateCust om erI DNam es procedur e with an int Size argum ent value of 25.
The first m essage box cont ains 25 row s, as do all t he intervening m essage boxes
up until t he last one. Th e last m essage box shows t he rows rem aining at t he end
that don’t fill an ent ire block of 25 rows.
Figur e 1 0 - 7 . The first an d last m essage boxes displayed by th e
En u m er a t e Cu st om erI D N a m e s proce du r e.

I n vok ing a St or ed Procedur e w it h a Par am et er by a SQL
St ring
I n addit ion t o using SQL st rings t o designat e t he data for the Com m and obj ect s
that populate DataReader object s, you can also specify a st ored procedure as t he
source for a Com m and obj ect . There are t wo m ain advantages to using st ored
procedures. First , st ored procedures are com piled. This saves t he server the t im e
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
of com piling a SQL st ring before it can st art t o return dat a for your Dat aReader
obj ect . Second, st ored procedures accept param et ers. This allows the users of
your applicat ions to change t he result set ret urned at run t im e.
There ar e two approaches t o set t ing param eter values for st ored procedures.
Many developers prefer t o specify a SQL st ring t hat invokes t he stored procedure
and passes t he value. Chapt er 4 illust rat es the synt ax for accom plishing this, and
we dem onst rate t he use of t he t echnique in a .NET Fram ework applicat ion wit h
the sam ple for t his sect ion. A second approach is to add param eters wit h the
.NET Fram ew ork syntax. This approach allows you t o explicit ly specify t he data

type as you pass a param et er. I will dem onst rat e t his second approach in t he
next sect ion.
The sam ple for t his sect ion and the next one depends on the Cust OrderHist
st ored procedure in t he Nort hw ind database. This procedure ret urns the quantit y
of each product ordered by a cust om er. The procedure takes a five- charact er
st ring param et er to designate t he Cust om erI D value. The result set cont ains a
single r ow for each product ever ordered by a cust om er. Each row cont ains the
product nam e and quant ity ordered by t he cust om er specified in t he param et er
when you invoke the st ored procedure. For y our convenience in understanding
the logic of t he CustOrderHist st ored pr ocedure, here’s t he T- SQL code for the
st ored procedure:
CREATE PROCEDURE CustOrderHist @CustomerID nchar(5)
AS
SELECT ProductName, Total=SUM(Quantity)
FROM Products P, [Order Details] OD, Orders O, Customers C
WHERE C.CustomerID = @CustomerID
AND C.CustomerID = O.CustomerID AND
O.OrderID = OD.OrderID AND OD.ProductID = P.ProductID
GROUP BY ProductName

Two sub procedur es m ake up t he solut ion for displaying the results from running
the Cust OrderHist st ored procedure w it h a SQL st ring. Th e first sub pr ocedure,
RunCustOrderHist Wit hSt ring, invok es t he SQL string for t he st ored pr ocedure and
creat es a Dat aReader obj ect based on its result set . RunCust OrderHist WithString
takes two argum ents— one for t he Custom erI D value and a second for specifying
the m ax im um num ber of r ows t o display as a block in a m essage box. This init ial
Visu al Basic .NET procedure:
• Creat es a Connect ion obj ect .
• I nst ant iates a Com m and obj ect that execut es t he Cust OrderHist st ored
procedure while passing a Cust om erI D value as a param eter.

• Populat es a DataReader based on t he result set fr om Cust OrderHist .
Because t he sam ple uses a SQL st r ing to invoke t he st ored procedure and pass a
param eter, t he pr ocess of running a st ored procedure wit h a param et er is sim ilar
to j ust specifying a SQL st ring as t he source for t he Com m and obj ect . This
sim ilarity is the chief advantage of using t he SQL st ring to inv oke the st ored
procedure. One disadvant age of t he approach is t hat t he server has t o com pile
the T-SQL st atem ent in t he st ring t o invoke the st ored procedure. Anot her
disadvant age is t hat you don’t get the benefit of explicit dat a t yping for t he
param eter value at t he client end of t he solut ion. This explicit typing can allow
you t o catch inappropriate param et er values earlier in t he solut ion and save
server t im e devoted to detecting er roneous param eter values as well as passing
back feedback on t he error t o the client.
The solution’s second sub procedure, drdToMessageBox, displays the rows in the
Dat aReader creat ed by RunCust OrderHist WithSt ring. The drdToMessageBox
procedure requires four argum ent s. The first t w o ar e passed by reference inst ead
of in t he norm al Visual Basic .NET way of by value. Th ese argum ent s are for t he
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Dat aReader obj ect and its associated Connect ion obj ect . The second tw o
argum ent s ar e passed by value. These are the Cust om erI D param et er value and
the value for t he m axim um num ber of rows t o display in a m essage box. The
design of t his second sub procedure is a direct extension of pr ior sam ples wit h
specific adj ust m ents, such as for t he title wit hin a m essage box. A specific benefit
of dividing the solut ion across t wo sub procedures is t hat we w ill be able t o reuse
this second sub pr ocedure in the next sect ion’s sam ple.
Sub RunCustOrderHistWithString(ByVal CustomerID As String, _
ByVal intSize As Integer)

’Declare and open connection to Northwind.
Dim cnn1 As SqlConnection = _
New SqlConnection(“Data Source=(local);” & _

“Integrated Security=SSPI;Initial Catalog=northwind”)
cnn1.Open()

’Declare command with T-SQL for a stored proc with a parameter.
Dim cmd1 As SqlCommand = _
New SqlCommand(“EXEC CustOrderHist “ & CustomerID, cnn1)

’Declare data reader and populate with result set
’from stored procedure.
Dim drd1 As SqlDataReader = cmd1.ExecuteReader()

’Display result set.
drdToMessageBox(drd1, cnn1, CustomerID, intSize)

End Sub

Sub drdToMessageBox(ByRef drd1 As SqlClient.SqlDataReader, _
ByRef cnn1 As SqlClient.SqlConnection, _
ByVal CustomerID As String, _
ByVal intSize As Integer)

’Declare header for report in message box and counter for rows
’showing within a message box.
Dim str1 As String = _
“Quantities for Products Ordered by “ & _
CustomerID & StrDup(2, vbCr)
Dim int1 As Integer

’Loop through data reader in blocks of intSize and
’sequentially display the contents of successive blocks.

Do While drd1.Read()
str1 = str1 & drd1.GetInt32(1) & vbTab _
& drd1.GetString(0).ToString & vbCrLf
int1 += 1
If (int1 Mod intSize) = 0 Then
str1 = str1 & StrDup(2, vbCr) _
& “Click OK for next “ & _
intSize.ToString & “ customers."
MsgBox(str1, , “From CustOrderHist Stored Proc”)
str1 = _
“Quantities for Products Ordered by “ & _
CustomerID & StrDup(2, vbCr)
End If
Loop

’If a partial block remains at end of data reader contents,
’display partial block.
If (int1 Mod intSize) <> 0 Then
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
str1 = str1 & StrDup(2, vbCr) _
& “Click OK to close message box."
MsgBox(str1, , “From CustOrderHist Stored Proc”)
End If

’Close data reader and connection object references.
drd1.Close()
cnn1.Close()

End Sub


You can run t he sam ple defined by t he preceding t wo sub procedur es from
Module1 in t he My ADODOTNETSam ples solut ion. The sam ple procedure call in t he
m ain procedure for invoking t he first procedure follows. I t passes t wo argum ent s
to the RunCust OrderHist WithString procedure. The first argum ent is a
Cust om erI D value, and t he second argum ent designates t he m axim um num ber of
rows t o display in a message box. You can obt ain a r esult set to disp lay for any
Cust om erI D in t he Cust om ers t able t hat has orders associated wit h it. (Tw o
Cust om erI D values don’t have any orders.) The solution aut om at ically populat es
t he argum ent list for t he second sub procedure that prints t he rows in t he
Dat aReader creat ed by the RunCust OrderHist Wit hSt r ing procedure.
RunCustOrderHistWithString(“TORTU", 10)

I n vok ing a St or ed Procedur e w it h a Par am et er by I t s Na m e
I t is possible to invoke a stored procedure and pass it param et er values without
using a SQL st ring. Som e developers w ould count this as an advant age. The
approach has t he extra advantage of st rong dat a t yping for paramet er values on
the client side of a database solut ion. Therefor e, illegitimat e values can be
det ect ed before encount ering t im e for a r ound-t rip t o t he server and wit hout
divert ing any valuable ser ver tim e to error pr ocessing. As t he scale of an
applicat ion grows relat ive t o server processing power and net work t hroughput ,
these considerations gain significance.
The solution to invoke a stored procedure w it hout a SQL st ring requires you to
assign t he nam e of t he st ored procedure as the Com m andText property for a
Com m and obj ect . You m ust also designat e Com m andTy pe.St oredProcedure as
the Com m andType pr opert y set t ing for t he Com m and obj ect . I f the st ored
procedure requires param et ers, you can invoke the Add m et hod for t he
Param et ers collect ion of the Com m and obj ect t o declare t he param et ers. As wit h
m any Visu al Basic . NET m et hods, t he specificat ion for t he Add m et hod of t he
Param et ers collect ion has m ult iple overloaded specificat ions. The one used in t he
sam ple for t his sect ion uses @Cust om erI D t o designat e t he param et er’s nam e.

The second and t hird argum ents for the Add m ethod designat e t he @Cust om erI D
param eter as a Unicode fixed lengt h text field of 5 charact ers. The sam ple follows
the param eter declarat ion wit h t he sy ntax for assigning an act ual value to t he
param eter. As you can see, you use t he param et er’s Value property to per form
this t ask .
Aside from the except ions not ed previously, the solut ion for running the
Cust OrderHist st ored procedur e with or w it hout a SQL st ring is t he sam e. You
creat e t he Connection obj ect ident ically, and you pass t he ret urn set from t he
Com m and obj ect t o t he DataReader obj ect in t he sam e way. Furt herm ore, this
second-solut ion approach uses exact ly t he sam e second sub procedure,
drdToMessageBox, t o display t he result set from t he CustOrderHist st ored
procedure in a series of m essage box es.
Sub RunCustOrderHistWithParameter(ByVal CustomerID As String, _
ByVal intSize As Integer)

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
’Declare and open connection to Northwind.
Dim cnn1 As SqlConnection = _
New SqlConnection(“Data Source=(local);” & _
“Integrated Security=SSPI;Initial Catalog=northwind”)
cnn1.Open()

’Instantiate a command reference pointing at the
’CustOrderHist stored proc.
Dim cmd1 As SqlCommand = _
New SqlCommand(“CustOrderHist", cnn1)
cmd1.CommandType = CommandType.StoredProcedure

’Declare the parameter with a SqlDbType to eliminate
’the need for conversion, then assign the parameter a value.

Dim prm1 As SqlParameter = _
cmd1.Parameters.Add(“@CustomerID", SqlDbType.NChar, 5)
prm1.Value = CustomerID

’Declare data reader and populate with its result
’set from the stored proc.
Dim drd1 As SqlDataReader = cmd1.ExecuteReader()

’Display result set.
drdToMessageBox(drd1, cnn1, CustomerID, intSize)

End Sub

You can invoke t he RunCust OrderHist Wit hParam et er procedur e from the m ain
procedure in Module1 for the MyADODOTNETSam ples solut ion. Sim ply rem ov e its
com m ent m arker and ensure t hat all ot her procedur e calls have a com m ent
m arker preceding t hem .
Crea ting a Da ta base Obj ect w it h a Com m a nd Obj ect
The Com m and obj ect prov ides m ore flexibility than j ust returning result sets. For
exam ple, you can use a Com m and obj ect to adm inist er a dat abase obj ect on a
SQL Server inst ance. This section dem onst rat es the capabilit y by adding a new
user-defined funct ion t o the Nort hwind database, using it, and t hen rem ov ing the
user-defined funct ion. For t his dem onst ration to work, your connect ion m ust be
based on a login with perm ission t o creat e w hat ever user-defined obj ect s you
at t em pt t o create or drop. See Chapt er 5 for the T-SQL synt ax on adding and
rem oving user - defined funct ions and Chapter 7 for a discussion of t he secu rit y
associat ed wit h logins t o a SQL Server instance. I f your login is t he adm inist rat or
for your local inst ance of SQL Server, you hav e appropriat e perm ission to run the
sam ple.
The user -defined funct ion udfDaysDiffLessx in t his sam ple com put es the

difference betw een two dat es m inus an offset . You can use t he funct ion to r eport
how m any days lat e an event occurred. For exam ple, if t he st andard for shipping
an order is wit hin 3 days of t he order date, you can use t his user-defined funct ion
to report how m any days after t he st andard an order ships.
The Creat eAndI nvokeUDF procedure in Module1 illust rates t he Visual Basic .NET
syntax for creat ing, using, and finally dropping a user- defined funct ion like the
one described. The Creat eAndI nvokeUDF procedure connect s t o t he Nor t hwind
database. The procedure takes t wo optional argum ent s. ( I f the user doesn’t
supply values for the argument s w hen calling t he procedure, t he procedure
assigns default values t o the argum ents.) The intOrderNo argum ent denot es t he
OrderI D value for the order about which you seek shipping inform ation, and t he
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
st rx argum ent is a st r ing representing t he offset in days bet ween two datet im e
values.
While som ewhat lengt hy, t he Creat eAndI nvokeUDF procedure design is
st raightforward. I n act ual pract ice, you are likely to ext ract the code for creat ing
a user - defined funct ion into a separat e sub procedure. The procedure begins by
m aking a connect ion t o the Nort hwind dat abase. Next t he procedur e defines a
SQL st ring for dropping any pr ior version of t he udfDaysDiffLessx user-defined
funct ion. The pr ocedure runs t his st ring from a Com m and obj ect with t he
ExecuteNonQuery m et hod. I n t he next code block, the procedure runs wit h t he
ExecuteNonQuery m et hod a second SQL string to creat e a new version of t he
udfDaysDiffLessx user-defined funct ion. Not ice t hat t he user- defined funct ion
includes a param et er t o specify the offset for t he difference bet w een tw o dat es.
After ensuring that the code for the user-defined funct ion is t he second SQL
st ring, the procedure runs a t hird SQL st ring that invok es the user- defined
funct ion wit hin a query st atem ent. The design of the SQL st ring for t he query
uses t he st rx argum ent as a var iable so t hat a procedure calling t he
Creat eAndI nvokeUDF procedure can dynam ically set t he offset bet w een t wo
dates. I n addit ion, t he int OrderNo argum ent is a variable in t he SQL st ring so t hat

a calling procedure can specify t he order via an OrderI D value on w hich t o report.
The procedure uses t he Execut eReader m et hod t o r un t he SQL st r ing in a
Com m and obj ect and passes the result t o a Dat aReader. After execut ing t he Read
m et hod for t he DataReader, a m essage box displays t he shipping inform at ion for
the order. The procedure concludes by perform ing various cleanup chores,
including rest oring t he Nort hwind dat abase so that the database no longer has a
user-defined funct ion nam ed udfDaysDiffLessx . I n pract ice, you m ay very well
decide t o keep a user-defined funct ion aft er creat ing it , but the sam ple runs this
st ep to rest ore your init ial copy of t he Nort hw ind database.
Sub CreateAndInvokeUDF( _s
Optional ByVal intOrderNo As Integer = 10248, _
Optional ByVal strx As String = “1”)

’Declare and open connection to Northwind.
Dim cnn1 As SqlConnection = _
New SqlConnection(“Data Source=(local);” & _
“Integrated Security=SSPI;Initial Catalog=northwind”)
cnn1.Open()

’Define SQL string to drop prior version of user-defined
’function, then run the T-SQL batch with ExecuteNonQuery
’method for a command.
Dim str1 As String = _
“IF EXISTS “ & _
“(SELECT * “ & _
“FROM INFORMATION_SCHEMA.ROUTINES “ & _
“WHERE ROUTINE_NAME = ’udfDaysDiffLessx’) “ & _
“DROP FUNCTION udfDaysDiffLessx"
Dim cmd1 As SqlCommand = New SqlCommand(str1, cnn1)
cmd1.ExecuteNonQuery()


’Define SQL string to create a new user-defined function,
’then run the T-SQL batch with ExecuteNonQuery method
’for a command.
str1 = “CREATE FUNCTION udfDaysDiffLessx” & _
“(@date1 as datetime, @date2 as datetime, “ & _
“@x as Integer) “ & _
“RETURNS int “ & _
“AS “ & _
“BEGIN “ & _
“Return(DATEDIFF(day,@date1,@date2)-@x) “ & _
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
“END"
cmd1.CommandText = str1
cmd1.ExecuteNonQuery()

’Define a SQL string to use the preceding user-defined
’function and accept variables for SQL string
’(strx and intOrderNo), then assign SQL string to
’CommandText property of command(cmd1).
Dim strSQL As String
strSQL = “SELECT LEFT(OrderDate,11) AS ’Order Date’, “ & _
“LEFT(ShippedDate,11) AS ’Shipped Date’, “ & _
“dbo.udfDaysDiffLessx(OrderDate, ShippedDate, “ & _
strx & “) AS ’Days Late’ “ & _
“FROM Orders “ & _
“WHERE OrderID = “ & intOrderNo.ToString
cmd1.CommandText = strSQL

’Store result set from SQL string in a data reader and

’format its contents for display via a MsgBox function.
Dim drd1 As SqlDataReader = cmd1.ExecuteReader()
drd1.Read()
str1 = “For Order “ & intOrderNo.ToString & vbCr & _
“OrderDate is “ & drd1.GetString(0) & vbCr & _
“ShippedDate is “ & drd1.GetString(1) & vbCr & _
“Days to ship after “ & strx & “ days is “ _
& drd1.GetInt32(2).ToString
MsgBox(str1, , _
“SQL string with a scalar user-defined function”)

’Restore the Northwind database by removing the udf.
str1 = _
“IF EXISTS “ & _
“(SELECT * “ & _
“FROM INFORMATION_SCHEMA.ROUTINES “ & _
“WHERE ROUTINE_NAME = ’udfDaysDiffLessx’) “ & _
“DROP FUNCTION udfDaysDiffLessx"
cmd1.CommandText = str1

’Close the data reader so the command can use it.
drd1.Close()

’Execute the SQL string to drop the user-defined function.
cmd1.Connection = cnn1
cmd1.ExecuteNonQuery()

’Finally, close the connection to the Northwind database.
cnn1.Close()


End Sub

The line in t he m ain procedure of Module1 invoking t he Cr eat eAndI nvokeUDF
procedure specifies an OrderI D of 10249 w it h int Or derNo and an offset of 3 days
wit h st rx. I n response t o invoking t he CreateAndI nvok eUDF procedure with t his
line, the procedure present s a m essage box like t he one in Figure 10-8. I f you
were interest ed in tracking perform ance on a next -day delivery prom ise, you
could replace t he value 3 in t he calling pr ocedure wit h 1.
Figur e 1 0 - 8 . The m essa ge box disp layed for ru nn ing the
Cre at eAn dI n vok eUDF procedu r e w it h t h e ar gu m en t s spe cified for it in
the m ain procedure of Module1 .
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.



Da taAdapters, D a ta Set s, Form s, a nd Form Cont r ols
This sect ion covers how t o place a data set behind a Windows form and allow
users t o interact wit h t he dat a set t hrough form contr ols. You will lear n how t o
bind SQL Server dat a t o the cont rols on a Window s form . Th is sect ion covers
several typical design applications such as att aching dat a t o t ext boxes, com bo
boxes, and dat a grids. The code sam ples and form designs illustrat e how to
m anage parent - child relationsh ips pr ogram m at ically in the data set behind a form
as well as int eract ively for a user through form controls. The sect ion closes with a
sam ple t hat dem onst rat es how t o dynam ically configure a Windows form based
on the data t hat it has to show.
Adding a Da ta Set t o a Form
A ty pical way of interact ing with dat a from Visual Basic .NET will be from
Window s For m s. While you can readily present m essage boxes t hat show the
Dat aReader content s, m any applicat ions will require a rich er form of dat a inte-
ract ivit y t han t he forward-only, read-only m odel support ed by the DataReader.

The key t o get t ing t o a richer m odel of data int eract ivit y is to place one or m ore
data set s in the m odule behind a form . The data set obj ect lets users navigat e
backward and forward in a dat a set. I n addition, users can update the data for
local use only or at a remot e data source. Any one dat a set can contain m ult iple
tables, and t he dat a set obj ect perm it s t he exist ence of hierarchical relat ionships
bet w een t he tables w it hin it.
The key t o populat ing a data set behind a form wit h data fr om a SQL Server
inst ance is to cr eat e a DataAdapter object t hat point s t o a dat a source on a SQL
Server inst ance. You can represent t he dat a source on the server wit h a SQL
st ring, a t able nam e, a view, or a st or ed procedur e. As wit h t he DataReader
obj ect , y ou can repr esent a SQL st r ing for t he DataAdapt er object with a
Com m and obj ect . The DataAdapter object has t wo m ain roles. First , it can fill a
data set behind a form . That’s t he focus of t his sect ion. Second, you can use a
Dat aAdapt er to updat e a rem ot e dat a source from the dat a set behind a form .
That’s t he focus of t he last m aj or sect ion in this chapt er .
Use the DataAdapt er obj ect ’s Select Com m and propert y to reference t he
Com m and obj ect specifying t he r em ot e dat a source for a Dat aAdapt er. Recall that
one im port ant role for a Dat aAdapter is t o copy t o t he dat a set behind a form .
Make t he rem ote data source available t hrough the DataAdapt er by opening the
connect ion for the Com m and obj ect . Copy t he dat a from the r em ot e data source
to the data set by invok ing the Fill m et hod of t he Dat aAdapter. I n t his t ype of
applicat ion, the DataAdapt er requires two argum ents— one referencing t he nam e
of the data set behind t he form and t he other nam ing t he table in t he data set .
You can designat e t he t ables w ithin a data set eit her by an index num ber
indicat ing the order in which you added t hem t o t he dat a set or by the nam e t hat
you specify as an argum ent to t he Fill m et hod.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
The Populat e procedure that follows illust rat es the syntax for copying a rem ote
data source to t he dat a set behind a form . This procedure is in t he m odule behind
Form 4, which I will discu ss in m ore det ail in t he next sam ple discussion. For now ,

j ust underst and that the Populate procedure is in a m odule behind a Windows
form . I ’ll be using several sam ples thr oughout the balance of this chapt er that are
variat ions of t his procedure, so I decided t o give the procedure a section of its
own t o help you focus on it .
N ote
The code for the Populate procedure assum es t he existence
of an I m port s st at em ent at the top of the m odule for t he
Syst em .Data.SqlClient nam espace.
I t ’s com m on to describe t he Dat aAdapter as a bridge bet ween a r em ot e dat a
source and t he data set behind a form . Therefor e, t he Populat e procedure starts
by declaring a Connect ion obj ect , cnn1. The cnn1 object refer ence points t o t he
Nort hwind database on t he local inst ance of SQL Serv er. Next t he procedure
declares and inst antiates a Com m and object , cm d1. A SQL st ring specifies the
CategoryI D, Cat egory Nam e, and Descript ion colum ns from t he Cat egor ies t ables
to designat e t he r esult set from cm d1. The Com m and object cm d1 links t o t he
Categories t able through t he Connect ion object cnn1. Aft er indirect ly specifying
the Com m andText propert y for a Com m and obj ect , the procedure inst ant iates a
Dat aAdapt er object and uses t he dap1 object reference to point t o it.
I n order for t he dap1 Dat aAdapt er t o fill t he dat a set behind the form , t w o
condit ions m ust hold. First , t he Dat aAdapter needs a Com m and obj ect assigned
to it s SelectCom m and propert y . Assigning cm d1 to the Select Com m and propert y
of dap1 sat isfies this condit ion. Second, the Dat aAdapt er requires an open
connect ion t o the Categories t able in t he Nort hwind database. I nvoking t he Open
m et hod for t he cnn1 object m eet s t his requirem ent . Aft er m eet ing these tw o
condit ions, t he procedure invokes t he Fill m et hod for dap1. The argum ents for the
m et hod in t he procedure designat e Categories as the nam e of t he DataTable
obj ect t hat holds t he result set from cm d1 in the das1 dat a set. The m odule
behind For m 4 declares and inst antiat es das1 as a dat a set at t he m odule level.
This m akes t he das1 data set available for use in all t he procedures behind a
form . Of course, it also m eans t hat y ou cannot see t he declarat ion in t he list ing

for the Populat e procedure. For y our easy reference, I include t he st atem ent
declaring and instant iat ing das1 just before t he list ing for the Populate procedure.
Notice that the Populat e procedure concludes by closing t he Connect ion object
cnn1. I n contrast to t he DataReader object , t he dat a set obj ect operat es while
disconnect ed from a rem ot e data source. Recall t hat t his abilit y to operat e while
disconnect ed adds t o the scalability of Visual Basic .NET applicat ions for SQL
Server.
’Module-level declaration of data set object.
Dim das1 As DataSet = New DataSet()

Sub Populate()
’Specify a connection for a data adapter that
’fills the data set used on the form.
Dim cnn1 As SqlConnection = _
New SqlConnection _
(“Data Source=(local);” & _
“Integrated Security=SSPI;” & _
“Initial Catalog=northwind”)

’Specify the command and data adapter that serves
’as the source for the data set on the form.
Dim cmd1 As SqlCommand = _
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
New SqlCommand _
(“SELECT CategoryID, CategoryName, Description “ & _
“FROM Categories", _
cnn1)
Dim dap1 As SqlDataAdapter = New SqlDataAdapter()
dap1.SelectCommand = cmd1
cnn1.Open()


’Fill the data set (das1) with the data adapter dap1;
’the Fill method populates the data set with a table
’named Categories.
dap1.Fill(das1, “Categories”)

’Close the connection because a data set is a
’disconnected data source.
cnn1.Close()

End Sub

Binding Cont rols on a Form t o Dat a
After populat ing t he dat a set behind a for m , y ou’ll want t o reference t he dat a set
wit h t he cont rols on t he form . One w ay to accom plish t his is to bind t he contr ols
to the data set . There are t wo st y les of data binding for cont rols. Sim ple dat a
binding m aps a colum n in a local data source, such as a Dat aTable in a dat a set,
to a propert y of a cont rol, such as t he Text propert y of a t ext box. Use t he
Dat aBindings collection of a cont rol to bind cont rol propert ies t o a colum n of
values in a local dat a source. Com plex dat a binding is a second way of binding a
cont r ol t o data. For t his st yle of dat a binding, a control— such as a com bo box, list
box, or data grid— binds to a collect ion of colum ns, such as a Dat aTable in a dat a
set . The sam ple in this sect ion dem onst rat es bot h approaches for binding cont r ols
to the Categories DataTable. The preceding sect ion described the code t hat
creat ed the Cat egories DataTable in the das1 dat a set for For m 4.
N ote
One int erest ing new developm ent with Visual Basic .NET is
the ability t o bind any property of a visible control, such as
it s BackColor or ForeColor propert y, to a colum n of dat a. This
feature opens t he possibilit y for a local data source

dynam ically controlling the form att ing of a form as well as
the dat a the form shows.
Figure 10- 9 show s Form 4. At t he left is t he form in Design view . At t he t op right
of the figur e is the form after it init ially opens. The bot t om right of t he figure
show s t he form aft er I select ed Confect ions from t he com bo box. Open Form 4 in
Design v iew by double- clicking Form 4.vb in Solution Explorer for t he
MyADODOTNETSam ples solut ion. Right -click t he solut ion’s nam e in Solut ion
Explorer, choose Properties, and select Form 4 as the st art up object t o make t he
form easy to launch (for exam ple, by pressing t he F5 key ).
The Design v iew of Form 4 rev eals t hat the form cont ains a com bo box wit h a
label, t w o t ext box es w ith labels, and a but t on. As show n in Chapt er 1, you can
graphically bind controls at design t im e. How ever , Form 4 program m at ically sets
the data binding for t he com bo box and t he two t ext box es. On t he other hand, I
set several cont rol features at design t im e. For exam ple, the Mu lt iline propert y of
Text Box2 is set t o Tr ue, while t he sam e propert y for Text Box1 has t he default
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
set t ing, False. The Mult iline property set t ing facilitat es Text Box2 show ing
Description colum n values t hat ext end over m or e t han one line.
Figur e 1 0 - 9 . A d esign- t im e view an d tw o ru n - t im e view s of Form 4 . The
t w o t ex t boxe s are pr ogr am m ed to u pd at e the ir cont ent s ba se d on th e
sele ct ion from t he com bo box.

The initial view of Form 4 shows t hat when it opens it displays t he first category.
Beverages appears in t he com bo box, and t he t wo t ext boxes show 1 as t he
CategoryI D and the descript ion for the bever ages product category. There is
nothing m andat ory about opening t he form for t he first category— any other
category will work equally well. The form synch ronizes the two t ext box es wit h
the com bo box. For exam ple, select ing Confect ions from the com bo box r evises
the cont ent disp layed in the t wo text boxes t o 3 and t he description for t he
confect ions cat egory .

To bind t he form controls to dat a set colum ns and m ake t he text boxes
dependent on t he com bo box select ion t akes just a few lines of code. I used five
lines of code to bind t he controls to dat a set colum n values and set t he cat egory
that appears w hen the form opens. This code appears in a form Load event
procedure for Form 4 t hat st art s by calling Populat e t o cr eat e t he das1 dat a set
described in t he preceding sect ion.
The event procedure puts das1 to use by binding t he Text propert y of TextBox1
to the CategoryI D colum n in t he Categories Dat aTable. You bind a column of
values t o a t ext box property by invoking the Add m et hod for the Dat aBindings
collect ion of a cont rol. The Add m et hod takes a Binding obj ect as an argum ent .
The argum ent s for t he Binding object specify the Text Box propert y t o bind (Text )
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
and t he colum n of values t o bind t o the property. This sam ple requir es two
argum ent s t o specify t he dat a source t hat binds t o t he t ext box propert y. First
designate t he dat a set nam e— das1. Second indicat e t he table nam e and colum n
nam e w it hin t he dat a set t hat you want t o bind to the propert y. Use a period
delim it er to separate the tw o nam es, as in Cat egories. Cat egoryI D. The Load
event procedure uses the sam e sy ntax to bind t he Descript ion colum n in t he
Categories DataTable t o t he Text propert y of TextBox2. Both dat a bindings
dem onst rate t he approach for sim ple dat a binding.
I t t akes a couple of lines t o bind t he com bo box to the Cat egories DataTable.
Act ually, one line does the binding, but a second line specifies the values t hat t he
com bo box displays for t he user t o m ake a select ion. Assign a Dat aTable to t he
Dat aSource propert y of a com bo box to bind t he com bo box t o the Dat aTable.
The syntax for specifying t he Categories t able used a nam ed argum ent for
denoting the t able in the dat a set. I could also have indicated t he Cat egories t able
by indicating its table index value, such as das1.Tables(0) . This sy nt ax
depends on t he t able index values not changing. After set t ing t he DataSource
propert y for t he com bo box, t he procedure assigns t he Cat egoryNam e colum n
from t he Cat egories Dat aTable as t he value for t he com bo box to display when

the user click s the cont r ol to m ake a select ion.
The final line of the form Load event procedure designat es t he posit ion in a
colum n t hat t he controls on For m 4 bound t o t he first table in t he das1 data set
are t o sh ow when t he form init ially opens. Position 0 point s t o t he first row in a
Dat aTable (for ex am ple, the Categories DataTable in t his sam ple). The Posit ion
propert y belongs t o t he BindingContext obj ect associated with a form . The
keyw ord Me denot es Form 4 in the last line of the form Load event procedure.
Private Sub Form4_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.Load

’Call the routine for creating the data set
’for the form.
Populate()

’Bind each text box to a different column in the
’Categories table of the data set (das1)on the form.
TextBox1.DataBindings.Add _
(New Binding(“Text", das1, “Categories.CategoryID”))
TextBox2.DataBindings.Add _
(New Binding(“Text", das1, “Categories.Description”))

’Bind combo box to Categories table in the
’data set (das1) on the form. Because the data set
’includes just one table, its index is 0.
ComboBox1.DataSource = das1.Tables(“Categories”)
ComboBox1.DisplayMember = “CategoryName"
Me.BindingContext(das1.Tables(0)).Position = 0

End Sub


The Select edI ndex Changed event procedure for the com bo box takes just one line
to synchronize the cont ent s of t he t ext boxes wit h the category nam e a user
select s from t he com bo box. The index values for a com bo box start at 0 for t he
first it em in the list for a com bo box. By set t ing t he com bo box’s Select edI ndex
propert y to the Posit ion propert y of the form ’s BindingCont ext obj ect , t he line
posit ions all cont rols on t he form t o t he sam e row a user select ed indirectly when
picking a category nam e from t he com bo box.
Private Sub ComboBox1_SelectedIndexChanged _
(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles ComboBox1.SelectedIndexChanged
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

’Use selected combo item as basis for text boxes.
Me.BindingContext(das1, “Categories”).Position _
= Me.ComboBox1.SelectedIndex

End Sub

Repor ting Dat aBindings
When work ing wit h a com plex form with m any cont rols w it h sim ple data bindings
or a form that you didn’t develop, y ou m ay find it convenient t o pr int a report on
the Dat aBindings collect ions for the cont rols on a form . A but t on on Form 4
invokes a procedur e that generat es such a report. Th e Click event for t his butt on
invokes a procedur e nam ed PrintBindingMem berI nfo in Module1 . You can also run
this procedure from out side a form t o report on the Dat aBindings collect ions for
the cont rols on a form .
As you can see from the following list ing, the Click event for the butt on m erely
calls t he Print BindingMem berI nfo procedure. However, t he call also passes a
reference t o Form 4 by using t he keyword Me as an argum ent. The

Print BindingMem ber I nfo procedure in t his sam ple is adapted from an ex am ple in
the Visual Basic .NET Help file. While the adaptat ion is subtle, it subst antially
enhances t he applicabilit y of t he procedure. First, t he adaptat ion works for any
form r eference passed t o it . The sam ple in t he Help file had t o be copied into t he
m odule for any form on which you sought a report . Second, you can run t he
adapted procedure ev en if you aren’t in t he form for which you seek a report. The
sam ple in t he Help file works only from a form t hat a user has open wit h t he
focus.
The Print BindingMem berI nfo procedure accept s a form reference as an argum ent.
For t he referenced form , t he procedure st art s a loop t o pass through all the
cont r ols on t he form . Within t he loop for t he cont rols on a form , t he procedure
runs a second loop to report any dat a binding for the current ly select ed cont rol in
the loop t hrough t he cont rols. I f t here are no data bindings for a cont r ol, t he
inner loop m er ely ret urns control t o the outer loop for t he cont rols. When all the
cont r ols on a form are looped t hr ough, the Pr int BindingMem berI nfo procedure
ret urns cont rol t o it s calling procedur e, which is t he Click event for Butt on1 on
Form 4 in t he following list ing.
’From module for Form4.
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click

’Display run-time binding settings specified in this module.
Module1.PrintBindingMemberInfo(Me)

End Sub

‘From Module1.
‘Adapted from Visual Basic .NET Help; the adaptation accommodates
‘any form as a passed argument and facilitates displaying run-time
‘bindings from outside a form.

Sub PrintBindingMemberInfo(ByRef MyForm As Form)
Dim thisControl As Control
For Each thisControl In MyForm.Controls
Dim thisBinding As Binding
For Each thisBinding In thisControl.DataBindings
’Print the control’s name and Binding information.
Console.WriteLine(ControlChars.Cr + thisControl.ToString(
))
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

×