When we create a connection using a SqlConnection object, we need to feed it the following connection parameters: ❑ Data Source – the name of the server where your data source is located
Trang 1A Brief Introduction to ADO.NET
Before we can begin creating our application we need to learn about some basic components of
ADO.NET and wizards that our application is to use We will go into greater detail on ADO.NET in thenext chapter so, for now, we'll learn just enough to get us through this simple database project
ADO.NET provides us with a way of gathering data and information and presenting it through a userinterface By using some components, we're able to connect to various data sources and can then build auser interface that accesses a database
We need four pieces to build our ADO.NET project:
Trang 2Basic Data Components
The Data Source
A data source is the term used to describe any collection of information that can provide data to us Itcan take the form of a database, an XML document, a Microsoft Excel spreadsheet, or even a flat text orbinary file It only takes one or two lines of code for us to change the kind of data source that weconnect to The Windows environment provides us a shared set of classes for use in our programs tocommunicate with these different sources using similar code
The Data Connection
The first thing we need to connect to a database is the data Connection object This comes in twoversions – either a SqlConnection or OleDbConnection object As we are working with the SQL
Server Desktop Engine, we will use the SqlConnection object.
When we create a connection using a SqlConnection object, we need to feed it the following
connection parameters:
❑ Data Source – the name of the server where your data source is located The data source can
be anywhere, be it on your network or somewhere over the Internet Usually, you will be
working on your local network and so you need to specify the name of the computer that holdsthe data source here Alternatively, we can give the name localhost or (local) to signifythat we want to use the computer that is actually running the application This terminology isused by many Windows applications when it is necessary to identify the current, local computer
❑ User ID and Password – the authentication details required to communicate with the datasource The ID and password is set up by the database administrator and helps prevent peoplefrom viewing or modifying the database without permission
Trang 3❑ Initial Catalog – this is the name of the database we want to work with – in this case,NorthwindSQL.
To create a new connection, we declare a new SqlConnection and set the ConnectionStringproperty using these parameters as shown here:
Dim myConnection As New SqlClient.SqlConnection()
myConnection.ConnectionString = "Data Source=localhost;" & _
"Initial Catalog=NorthwindSQL;User
Id=sa;Password=sa;"
Alternatively, we can pass the connection string as a parameter to the SqlConnection as follows:
Dim myConnection As New SqlClient.SqlConnection("Data Source=localhost;" & _
"Initial Catalog=NorthwindSQL;User
Id=sa;Password=sa;""
Creating a new OleDbConnection object is similar, except that we also need a Provider parameter
to describe the type of data source that we are connecting to So why don't we need that parameter withthe SqlConnection object? You've got it – because the provider type will always be SQL and, in fact,
if you do try to set the Provider parameter for an SqlConnection object, you will get an error
Now we can look at the component that requires a data Connection object to be set up in order tofunction, namely the DataAdapter
The DataAdapters
The DataAdapter is the mechanism that sits between the data source and the DataSet We have twotypes of DataAdapters, the SqlDataAdapter, which is used exclusively for SQL Server databases,and the OleDbDataAdapter, which is used for all other data sources and goes through another layercalled OLE DB Consequently, by avoiding the need for this extra layer, the SqlDataAdapterprovides much faster access to data The OleDbDataAdapter can be used to access SQL Server but,
as it then goes through the OLE DB layer, you are well advised to stick with the SqlDataAdapter foroptimum performance if you don't anticipate using anything other than SQL Server This applies to our
Trang 4As we are dealing with a SQL database, we will be working with the SqlCommand object (as opposed tothe OleDBCommand object) When we use the DataAdapter Wizards, for each table you work with youwill have a corresponding DataAdapter When we use the Wizards, the DataAdapters are configuredspecifically for the chosen table such that all of the methods for updating and retrieving information point
to that specific table To re-use the adapter for another table, we have to essentially rebuild the objects thatmake up the DataAdapter, which means all of the Command objects The simpler solution is to assignone DataAdapter per table, and this helps keep your code nice and clean and easy to maintain Whenyou build a DataAdapter, you can specify more than one table if needed For example, we could create
a DataAdapter that links the Customers table and the Orders table – to enable us to view informationfrom both tables using a single DataAdapter, without needing any code to link them This method oflinking multiple tables into a single view doesn't work really well when it comes to updating information,however, as the DataAdapter Wizard isn't able to properly link tables together to cascade updates ordeletes, reinforcing the case for using one DataAdapter per table
This diagram shows the basic structure of a DataAdapter:
DataAdapter Command Objects SelectCommand InsertCommand UpdateCommand DeleteCommand
The DataSet
Finally, a DataSet is a container or collection of tables; it can contain one or more tables and ismaintained in memory Relationships between tables are also stored here The tables it holds contain
information such as customer details or product information in the form of records, or rows A table
may consist of thousands of such rows
Table1 Table2 DataSet
DataSet
Trang 5One useful illustration is to think of a DataSet as holding details of a book publisher A technical publishermight publish books in several categories such as NET, Java, ASP, and C++ Within each category areindividual books – so that a NET category could have books such as Professional VB.NET, BeginningVB.NET, Professional C#, and Introducing NET A table could represent each of these categories, and eachbook in a category would be represented by a row in the appropriate table Each row holds details for eachbook – for example, title, price, ISBN number, publishing date, and the number of pages.
Each publisher can publish
books for several categories
Each category can contain several books
Book Details:
Title = Professional VB.NET Price = $59.99
ISBN = 1861004974 Published = August 2001 Pages = 950
.NET Professional VB.NET Beg VB.NET Professional C#
Publisher Book Catagories
There is no limit to the type of information you can store in a DataSet Now that we have looked atthe internals of a DataSet, let's take a look at how we can put one to use in an application Thecomponents shown in the figure below will be demonstrated in our application:
Customer Table Components
DataSet
Trang 6For our program, we will need to create a SqlDataAdapter object to select customer records from theNorthwind database via a SqlConnection object This connection will be opened only long enough
to complete the SQL SELECT operation Our DataSet will be populated with data from our customer
table using the SqlDataAdapter object Linking, or data binding, to a visual component such as the
DataGrid control will then display the DataSet's contents on a Windows Form
Now we can begin implementing these components in our simple database application Here's anoverview of the tasks ahead:
❑ Creating a Windows Application
❑ Connecting to a data source
❑ Adding a DataAdapter to our form
❑ Generating a DataSet from the DataAdapter
❑ Adding a DataGrid control to our form
❑ Displaying the contents of a customer table in our DataGrid
We start by creating a new Visual Studio NET application and then adding a SqlDataAdapter to theproject We'll also have to create a connection to the NorthwindSQL database for the DataAdapter.From the SqlDataAdapter we'll create a new DataSet Once we have a DataSet, we will add aDataGrid to our form and bind the DataSet to it Lastly, we'll add a button that fills the DataSetwith customer records and displays it in the DataGrid
Visual Studio NET's configuration wizards provide us with an easy way of doing all this We're just apoint and click away from creating our database application!
Try It Out – Creating a DataAdapter
5. Create a new Visual Basic NET Windows Application You can create this project in anydirectory Name the project CustomerApp and click OK
Trang 76. A new form will automatically be generated called Form1 Add a SqlDataAdapter to theform by double-clicking the SqlDataAdapter component from the Data tab of the Toolbox,usually found to the left of the Visual Studio screen.
Trang 87. Click Next when the welcome page of the DataAdapter Configuration Wizard appears tobring up the window shown in the following screenshot, prompting for a connection to adatabase If we had created other data connections already, they would be shown in the drop-down list Since this is our first time connecting, however, it will be empty and we must create
a new connection by clicking the New Connection button
8. Now we are presented with the Data Link Properties window In the top drop-down list forselecting the server name, if you can find your computer's name there, then choose it –
otherwise type in localhost or whatever is the server name where the SQL Server containing theNorthwindSQL database resides In item two, you choose to either use your current Windowslogon details to authenticate or to enter a different user name and password as used by SQLServer You should try selecting the Windows NT Integrated security first as this often works; if
it doesn't, then try a specific username and password as set by the database administrator In thiscase we use a SQL Server ID of sa (for system administrator) with no password In general, ofcourse, you would not use a blank password because of security concerns Item three requiresyou to choose an existing database on the server, so type in NorthwindSQL here Click the TestConnection button to test your connection if you wish, although you can be fairly sure that theconnection is valid if the correct list of databases appears in item three's drop-down
Trang 99. Click OK to proceed, and then Next to get to the Chose a Query Type window for determiningthe access method for the data in the Northwind database You can use a SQL statement, or new orexisting stored procedures For the first option you must specify the SQL statement to use Thesecond option also asks you to specify a SQL statement but, this time, the wizard will create
Trang 1010.Now we need to enter the SELECT statement for selecting our customer records Turn back toChapter 3 to refresh your memory of SQL commands if you wish We will be using the QueryBuilder to help us build a SQL statement rather than typing in a SQL statement directly Thebuilder is similar to the one provided with Microsoft Access and SQL Server First, we need tochange some options so click the Advanced Options button.
Trang 1111.This advanced dialog gives us three options The first option tells us that all of the SQL commands
to insert, update, and delete will be generated based on your SELECT statement
We will only be viewing data from the database with SELECT statements so unselect the first checkbox, which then disables the remaining check boxes I shall briefly describe the other options now,should you wish to use them in later applications Use optimistic concurrency generates UPDATEand DELETE statements that check to make sure that none of the columns have changed since weretrieved the original records, to prevent data from being changed by more than one user at thesame time The Refresh the Dataset option generates a SELECT statement after each UPDATE orDELETE statement, so that the updated row will also be updated in your DataSet
Trang 1213.Next, select the columns to display: CustomerID, CompanyName, Address, City, Region, andPostalCode As you select columns, the SELECT statement will change accordingly Once youhave selected all of the columns, right-click anywhere in the Query Builder area to bring upthe context menu, and select Run to show the query results in the area below.
Trang 13This context menu lets you add additional tables if you want but, for now, we will leave it as is You canalso specify an alias for each column, which can be useful if the names in the database don't match yourconventions or are not obvious.
As an example, set the Alias of CompanyName to Company and PostalCode to Zip Notice how the
Trang 14We won't be using the Alias feature so remove any you may have set before continuing When finished, click OK.
14.Our new SELECT statement should now appear in the dialog Check that it is correct and click Next
The last screen provides us with a summary of the wizard's actions Click the Finish button
Trang 15Two components will now be placed under the form in your project: SqlDataAdapter1 andSqlConnection1.
Trang 16Building the Data Container
We need to build a data container to hold our results The data container we shall use will be a DataSet
Try It Out - Generating a DataSet
1. Generate a DataSet by right-clicking on the SqlDataAdapter1 control and selectingGenerate Dataset
Trang 17This context menu provides some other options that you may find useful at some point ConfigureDataAdapter lets you reconfigure the DataSet, taking you through a similar sequence of steps as wejust followed when building our DataAdapter We can also preview the data in our DataAdapterwith the Preview Data option If you select this item you will see a screen as shown:
Trang 18The Data adapters drop-down box shows a list of all DataAdapters in your project Selectthe DataAdapter you want to view the data of, in this case SqlDataAdapter1, and thenclick the Fill Dataset button This will call the Fill method of the DataAdapter and willshow you the results obtained The Target dataset drop-down lists all DataSets in yourproject If, as in our case, there are none yet, it will show Untyped Dataset as the defaultDataSet This is a sort of temporary DataSet for displaying the results The Parametersarea shows any parameters required to run the SQL SELECT statement or stored procedureassociated with the selected DataAdapter Clear Results will clear the results shown if youwish to regenerate the results or choose another DataAdapter.
2. Going back to the context menu, at the Generate Dataset dialog, select the option to create anew DataSet and enter the name CustomerDataSet Check the Add this dataset to thedesigner box to indicate that we want the new DataSet object added to the initializationsection of our form, and for it to be instantiated Whether or not this box is checked, an XMLschema file is generated that defines the structure of the tables within our DataSet We willlook at XML and its role in ADO.NET in Chapter 12 Click OK when finished:
We should now have a DataSet control on our form called CustomerDataSet1, as well as anassociated XML schema file called CustomerDataSet.xsd Our form should now containthe three components shown below:
Trang 19How It Works
The purpose of these steps was to create a new DataSet object called CustomerDataSet1 Whenever wereference the DataSet, we will use the name CustomerDataSet1 This is not to be confused with the actualDataSet name of CustomerDataSet Also, note that the DataSet is empty until we populate it through theDataAdapter in code The wizard generates code to link the DataSet to the XML schema file,
CustomerDataSet.xsd This XML schema describes the layout of the DataSet, based on the columns that
we selected in the Query Builder We won't be using the XML features of the DataSet here, so we don't need
to concern ourselves with it yet (Chapter 12 looks at XML in detail) SqlDataAdapter1 contains our SELECTstatement to retrieve data from the Customers table, and it connects to the database using SqlConnection1– remember that we need both a DataAdapter and Connection object to get data from a database
Binding Data to Controls
Most of the controls in the Toolbox are bindable, which means that we can assign a column, or sometimes agroup of columns, from a database table to be displayed as their contents As you move through the rows of atable, the contents of the chosen column or columns will appear in the control Other bindable controls includeTextBoxes, Labels, CheckBoxes, ComboBoxes and ListBoxes Most of these controls work by setting theirDataBindings.Text property to the name of the table column that you want to bind to According to theproperty you're dealing with, you would check the DataBinding properties for a corresponding property toset – with experience you will learn which controls support which data binding properties Other controls likethe DataGrid use the DataSource and DataMember properties for binding DataGrids are capable ofshowing the data in all columns of a table, rather than just one Combo and ListBoxes use a DataSource andDisplayMember property and work similarly to TextBoxes in that they only show single columns of data
To populate a ListBox or ComboBox with data taken from a given column, set their DataSource andDisplayMember properties appropriately There are two methods for displaying data:
3. As a bound list – this will display a list of items in the control and will be in synch with anynavigation control on the form The control can also act as a navigation control so that, whenyou select a different record to display, all other bound controls change in synch to display therelevant data of the new record This is done by setting the DataSource property to a DataSetobject and the DisplayMember property to the column name of the table, as shown here:
Trang 204. As a general list – this will display a list of items in the control and will not change to match
any navigation controls This is achieved by setting DataSource to a DataSet.Table objectand DisplayMember to a column:
You can apply these same methods and properties when using a ComboBox
To populate the Checked property of a CheckBox, set the DataBindings.Checked property to aBoolean (True or False) column of the database:
The RadioButton control is a little different to the CheckBox We really only have one useableDataBindings property: the Text property There is also a Checked property, but it's hidden underthe Advanced property Click on the Advanced property's ellipsis button (…) to bring up the
Advanced Data Binding dialog:
Trang 21Under the Advanced Data Binding dialog we can set the Checked property As a matter of fact, we can setany property in this dialog to a column in a database, as long as that column is of the correct type orformat for that property:
Trang 22Besides setting these controls by pointing and clicking, we can also bind these controls at runtime,which would allow us to display different tables or columns in our controls, based on a user's request Inthis way, we can use just one control to display a variety of information, instead of limiting each control
to displaying a single set of data The following code shows how to bind to a control manually:
TextBox1.DataBindings.Add("Text", CustomerDataSet1, "Customers.Address")
The arguments of the DataBindings.Add method are the DataBinding property of the control wewish to set (Text in this case) For every property of a control that you want to set, you should checkfor a matching DataBinding property The remaining two parameters are the DataSet
(CustomerDataSet1) and the table name plus column name, separated by a period
(Customers.Address)
An alternative way to call the DataBindings.Add method is to pass in a Binding object:
Dim myBinding As New Binding("Text", CustomerDataSet1, "Customers.Address")
TextBox1.DataBindings.Add(myBinding)
Let's take a look at some other common controls and their data-binding properties for the display of data:
Control Property Example
TextBox Text TextBox1.DataBindings.Add("Text", myDataSet,
"Customers.Address")
"Customers.Address")Check
Box
Text CheckBox1.DataBindings.Add("Text", myDataSet,
"Products.ProductName")Checked CheckBox1.DataBindings.Add("Checked", myDataSet,
_ "Products.Discontinued")Radio
Button
Text RadioButton1.DataBindings.Add("CheckState",
myDataSet, _ "Products.ProductName")Checked RadioButton1.DataBindings.Add("CheckState",
myDataSet, _ "Products.Discontinued")
DisplayMember = myTable.myColumnNameCombo
Trang 23Bound Controls TextBoxes display
data from current row
DataGrid
displays all
rows
Select * From Customers
Row CurrentRow Row Row
Table DataSet
Northwind Database City
All Rows
Address
Try It Out - Adding a Data Bound DataGrid
In this section, I'll take you through the process of adding a bound control to our project
1. Add a DataGrid from the Windows Forms tab in the Toolbox to Form1 of the
CustomerApp project
Trang 243. Set DataGrid1's DataSource property to CustomerDataSet1 and set the DataMemberproperty to Customers.
How It Works
We have added a DataGrid and button to the form By setting the DataSource and DataMemberproperties, we tell the DataGrid to bind to our DataSet and that we want to show the Customerstable Once these properties are set, the grid will automatically be bound to the table specified and thecolumns will be formatted with the columns from our SQL SELECT statement, as shown below:
Trang 25Displaying Database Information to the User
One thing our wizards didn't do is add code to actually fill the DataSet with the desired informationfrom the database We have to call the Fill method of the DataAdapter to accomplish this Double-click on the Get Data button in Visual Studio, and add the following for the click event:
Private Sub btnGetData_Click(ByVal sender As System.Object, _
Trang 26It's that easy!
So what's going on to make this work?
1. From the user interface – our Windows Form – we click the Get Data button, which calls theFill method of the SqlDataAdapter to tell the database that we want some records
2. Next, the SqlDataAdapter requests a connection to be opened through the
SqlConnection object
3. The SqlConnection object uses the logon information we provided to open a connection tothe database Once the connection is opened, a SelectCommand is issued to actually retrievethe records As you may remember, this command is created from a SqlCommand object
4. Once the connection is open and we issue a SELECT command, the results are sent throughthe connection
5. The results are then passed through the SqlDataAdapter.
6. Finally, the SqlDataAdapter populates the DataSet
Trang 27Customer Table Components
SqlConnection
Windows From DataSet Customers
6.) Returns data 1.) Calls Fill method
SqlDataAdapter
5.) Returns data
2.) Request to open connection/
Issues SELECT command
4.) Returns customer listing
3.) Opens connection
Northwind Database
Once we have filled our DataSet, the connection is closed and we are free to use the DataSethowever we wish In the last example, we displayed the data on the user interface by binding theDataSet to a DataGrid control on our Windows Form
What's Behind the Curtain?
Trang 28End Sub
'Form overrides dispose to clean up the component list
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
Friend WithEvents DataGrid1 As System.Windows.Forms.DataGrid
Friend WithEvents btnGetData As System.Windows.Forms.Button
Friend WithEvents CustomerDataSet1 As CustomerApp.CustomerDataSet
Friend WithEvents SqlSelectCommand1 As System.Data.SqlClient.SqlCommand
'Required by the Windows Form Designer
Private components As System.ComponentModel.Container
We can see the standard constructor and destructor code here, and then we have declarations for ourDataAdapter, SQLConnection, DataGrid, Button, DataSet, and SqlCommand These are justdeclarations and do not create actual instances just yet You can trap events created by these objects ifneeded, since they are declared with the WithEvents keyword The Friend keyword signifies thatthe declaration is valid anywhere within the same assembly or program, so we can reference theseobjects anywhere in our program
Let's look at the InitializeComponent procedure Instances of our DataAdapter,
SqlConnection, DataGrid, Button, DataSet, and SqlCommand objects are set up here:
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer
'Do not modify it using the code editor
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() Me.SqlDataAdapter1 = New System.Data.SqlClient.SqlDataAdapter()
Me.SqlConnection1 = New System.Data.SqlClient.SqlConnection()
Me.DataGrid1 = New System.Windows.Forms.DataGrid()
Me.btnGetData = New System.Windows.Forms.Button()
Me.CustomerDataSet1 = New CustomerApp.CustomerDataSet()
Me.SqlSelectCommand1 = New System.Data.SqlClient.SqlCommand()
To prevent other objects from accessing our controls, we call the BeginInit method on our
DataGrid and DataSet objects:
CType(Me.DataGrid1, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.CustomerDataSet1,
System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
These are called to avoid any access to these components before initialization Certain controls requirethat some properties be initialized before others in order to work properly By using BeginInit, wetemporarily place our control in a frozen state, preventing any events or validation from occurring Notall controls have this requirement so, if you come across a control that doesn't support this method, youcan safely assume that it doesn't need initializing in a particular order like those here do
Trang 29In this next block of code, we assign our SELECT statement reference:
'
'SqlDataAdapter1
'
Me.SqlDataAdapter1.SelectCommand = Me.SqlSelectCommand1
We set the SelectCommand property to our SELECT statement so that, when we later call the
DataAdapter's Fill method, this statement will get executed In the code below, we assign the tablemappings, table name, and column names:
New System.Data.Common.DataColumnMapping("Address", "Address"),
New System.Data.Common.DataColumnMapping("City", "City"),
New System.Data.Common.DataColumnMapping("Region", "Region"),
New System.Data.Common.DataColumnMapping("PostalCode",
"PostalCode")})})
By default, when you create a new table, it is simply called Table but, since we're using the Customerstable, it is renamed We also have our column mappings We didn't change any of the column names inthe Query Builder so all of the names will be left with their original names If we had used an alias whenbuilding our SQL statement and used Company for CompanyName, for example, it would be mappedwith the new name provided as the second parameter This section of code builds the DataSet'sstructure in memory We use the DataAdapter to fill this in-memory object with data
Next, the connection string is made up from the parameters for connecting to the database These sameproperties were set in the Data Link Properties dialog earlier and, consequently, your connection stringmay vary slightly from this one:
Trang 30The behavior of the DataGrid gets configured next:
Me.btnGetData.Text = "Get Data"
The TabIndex is set to one, indicating that it will be the second tab item The button Text property sets thelabel to show on the button, which is "Get Data" in this case Properties of our DataSet are then set:
'
'CustomerDataSet1
'
Me.CustomerDataSet1.DataSetName = "CustomerDataSet"
Me.CustomerDataSet1.Locale = New System.Globalization.CultureInfo("")
Our DataSet object, which is called CustomerDataSet1, uses the DataSet name of CustomerDataSet
The Locale property is set to a CultureInfo object This class holds culture-specific information, such aslanguage, sublanguage, country/region, and cultural conventions This class also provides the information toperform certain tasks, such as formatting dates and numbers, sorting and comparing strings, and determiningcharacter type information The culture information is based on which country you are in For example, youmight specify "en-AU" which is English – Australia, "en-GB" which indicates English – United Kingdom,and "en-US" which is English – United States There are many other specifiers available for you to use Ifyou don't specify a type, then the culture information specific to your computer will be used
The Namespace property is used when reading and writing an XML document into the DataSet usingthe ReadXml, WriteXml, ReadXmlSchema, or WriteXmlSchema methods:
Me.CustomerDataSet1.Namespace =
"http://www.tempuri.org/CustomerDataSet.xsd"
By default, this points to www.tempuri.org You can point this to your website or directory to readthe schema You can also leave this as is and it will work without any problems Again, we will get ontoXML and its role in ADO.NET in Chapter 12
Trang 31The records from the database become available for retrieval when a connection is opened and a SQLstatement is executed, as shown here:
statement, we assign a connection so that, when the command is executed, it opens the connection specified
The code for the other controls on the form (the Button and DataGrid) is added to the
Controls.AddRange method This is used by the Windows Form to track all of the controls that are
on the form It also exposes the ability for the developer to iterate through the controls collection on aform We then call the EndInit methods of the DataGrid and DataSet to let the system know that
we can now access the components
'
'Form1
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(520, 237)
Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.btnGetData,Me.DataGrid1})
Me.Name = "Form1"
Me.Text = "Form1"
CType(Me.DataGrid1, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.CustomerDataSet1,
System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
End Sub
Trang 32❑ We created a SQL SELECT statement to retrieve customer information
❑ We created a SqlCommand object to call our SQL SELECT statement
❑ The command was configured so that, any time that we select records, a connection is opened
by assigning the Connection object to the SqlCommand object
❑ We configured a DataAdapter, SqlDataAdapter1, to return the appropriate records anytime that we call the Fill method
❑ We created a new DataSet to hold our tables
❑ We configured our DataGrid so that it displays the Customers table using the DataSet
❑ We called the Fill method, which filled our table up with customer records and displayed it
in the DataGrid
Adding Additional Tables
We have seen how to display a single table to the user What if we wanted to display multiple tables?
We can add more tables to view in our DataGrid by adding another SqlDataAdapter For example,
if we want to view suppliers in our DataGrid, we can add another DataAdapter and use the same
connection to display this information
Trang 33Connection to multiple Tables
SqlDataAdapter1
SqlConnection1
Northwind Database
Customer DataSet
Customers
Suppliers
SqlDataAdapter2
Try It Out - Adding a Second DataAdapter
In this section, I will take you through the steps for adding an additional DataAdapter
1. In the form design view, add another SqlDataAdapter control to your form from the Datatab of the Toolbox You will be guided through the same steps that we followed earlier
As you will notice, this time an existing data connection is listed from the connection wecreated earlier This will show up as Computername.NorthwindSQL.dbo, where
Computername is the name of the computer that you're connected to Click the Next button
Trang 345. Again, we'll be back at the previous window Review the SQL statement and click Next.The final dialog will appear Click Finish This will add a new DataAdapter called SqlDataAdapter2below your form.
6. Next we need to update our existing DataSet to hold this second table Right-click onSqlDataAdapter2 and select Generate Dataset The Generate Dataset window willappear and we can choose to use the existing DataSet or create a new one We will use theexisting one Also, there will be a list that shows two tables: the Customer table (our originalone) and now the Suppliers table The Suppliers table will already be selected so just click
OK This will add the table to the existing DataSet