Académique Documents
Professionnel Documents
Culture Documents
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
20
20
• Learn to bind data to the user interface
• Get acquainted with displaying and updating data
• Discover how to transform and filter data
• Access and manipulate data from a Microsoft SQL Server database
• Be introduced to handling data errors
This chapter deals with the data-specific portions of the C# Windows exam and assumes
a good working knowledge of the information in Chapter 10. If you have not had a
chance to review Chapter 10, which presented the concepts of the ADO.NET object
model, now would be a good time. You will also find information pertinent to both the
Windows and the web exam in Chapter 10. In order to prepare you for the C# Windows
exam, we will now take those concepts and apply them to Windows Forms. We will ac-
cess data from Microsoft SQL Server 2000 using our college application introduced in
the last two chapters.
In the past, Microsoft has tended to test heavily on the data side, and you can expect
no less on the .NET exams. We will focus on two data-access techniques. The first takes
advantage of the Visual Studio .NET support for accessing data—you will find a number
of ADO.NET objects in the Toolbox that can be added to your form in order to assist
with data access. The second technique involves coding using the ADO.NET object
model—using objects such as Connection, Command, DataSet, and so on. These ob-
jects were introduced in Chapter 10, and we will use them in our Windows Form in this
chapter.
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:17 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
20
EXAM TIP Commit the objects in Table 20-1 to memory. You will be tested
on your knowledge of each of these objects.
There are a number of classes that assist with data representation, and they are inde-
pendent of the source of the data (whether it be SQL Server, Oracle, or something else).
These classes include DataRow and DataColumn, which as their names imply, repre-
sent rows and columns from a table (or spreadsheet), respectively. There is also a
DataTable class, which represents the collection of row and column data, and a
DataRelation class, which acts as a link between two DataTable objects. You can
consider a DataTable to be a collection of DataRow objects, and a DataRelation to
be the foreign-key representation between two DataTable objects.
EXAM TIP Be sure that you understand the source-specific classes for
setting up the connection to your data. These include SqlCommand and
SqlConnection for specifying the SQL statements or stored procedures
and the connection parameters when accessing Microsoft SQL Server 7.0
(and higher) databases. In order to connect to an OLE/DB provider other than Microsoft
SQL Server 7.0 (and higher), you would use OleDbCommand and OleDbConnection.
The classes specific to these two types of data stores are included in the ADO.NET object
model. If you wish to access data providers other than these types, you must download the
ODBC classes from Microsoft.
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:18 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
20
PART III
The College Application
Our college application was developed in the last two chapters and will be expanded to
include a visual presentation of the data found in our database. Figure 20-1 shows the
schematic of the College database, which includes three tables—Student, Program, and
Course.
The Student table includes information about the students in our sample college, in-
cluding the program in which they are enrolled. The program is linked to the Program
table for a description and to the Course table for the list of courses that a student must
take to complete the program. Using this simple database, we will be able to demon-
strate the capabilities of data access, along with some relational aspects.
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:18 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
20
Figure 20-2
The ADO.NET
Toolbox
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:18 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
20
TIP Be sure to test the connection. The wizard provides you with a Test
Connection button that will ensure that a connection can be made to the
PART III
database server.
You also have an opportunity to change the provider using the Provider tab of the
Data Link Properties window (see Figure 20-5). Take a moment to investigate the differ-
ent data providers offered by default within Visual Studio .NET. Should you have need
of any other data providers, you will have to download it from either Microsoft’s web
site or the vendor’s web site.
Figure 20-3
Choose your
data connection
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:18 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
20
Figure 20-5
Set a data
provider
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:19 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
20
• Use SQL statements These are SQL statements that you code yourself,
and they could be SELECT, UPDATE, DELETE, or INSERT statements.
• Create new stored procedures This lets you create your own stored
procedures.
• Use existing stored procedures This allows you to use stored procedures
that already reside on the database server.
For this example, choose to use your own SQL statements. Click the Next button, and
the wizard will ask you to type in the SQL statement (see Figure 20-7). You have three
PART III
choices when presented with this wizard window:
EXAM TIP You should be very comfortable with the standard SQL
statements. Review Chapter 10 for SELECT, UPDATE, DELETE, and
INSERT statements.
Figure 20-6
Choose a
query type
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:19 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
20
For the purposes of this example, turn off the automatic generation of SQL state-
ments offered in the Advanced options by unchecking the Generate Insert, Update, and
Delete Statements check box.
If you select the Query Builder, the Add Table dialog box opens (see Figure 20-9), dis-
playing a list of the tables contained in the database that was specified in the Data Link
Properties dialog box. Select the tables you wish to add (for this example, choose the
Student table), and the Query Builder will provide you with a graphical interface for
completing your SQL statements, as shown in Figure 20-10. The tables you add can then
be used in any query string that you build through the Query Builder.
Figure 20-8
The advanced
options
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:19 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
20
PART III
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:20 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
20
You can also specify the sort order and selection criteria in the second pane.
To test the command, right-click in the bottom pane and select Run. The command
will be run against the connection to the database, and the results will be shown in the
bottom pane.
In this example (shown in Figure 20-10), we have asked that LastName be sorted as-
cending, then FirstName sorted within LastName. We also specified that the FirstName
must be equal to ‘Jim’. As you can see in the figure, this command returned only one
record where the first name is ‘Jim’. The corresponding SQL statement has been gener-
ated for us:
Once you have tested the command, click OK in the Query Builder, and click Next in
the Data Adapter Configuration Wizard. The wizard then uses the information that you
provided to generate the desired command and connection statements. You will be
shown a window that verifies the success or failure of the exercise (see Figure 20-11).
When you are satisfied with the results, click Finish. You will be returned to your
form. Notice in Figure 20-12 that the form now has two objects associated with it—
sqlDataAdapter1 and sqlConnection1.
Figure 20-11
Configuration
Wizard results
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:20 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
20
PART III
Figure 20-12 The form with the data adapter and connection
You have now created two objects that represent the execution instructions and the
physical connection to the data store. The next step is to create an object that will repre-
sent the data—a DataSet. There are two ways to accomplish this:
In either case the Generate Dataset dialog box will be displayed (see Figure 20-13).
You can select either an existing dataset or create a new object. For this example, choose
a new DataSet object and call it dsStudent to represent the table from which the data
is retrieved. The new DataSet object (dsStudent1) is created and added to the form
along with the DataAdapter and Connection objects (at the bottom of the screen).
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:20 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
20
NOTE Your output may not look exactly like Figure 20-14. As a matter of fact,
unless you have read ahead, you will notice that you have no data from the
database displayed. You must manually put data into the DataSet using the
Fill method of the DataAdapter. We will cover this in the next section.
Figure 20-14
The DataGrid
control
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:21 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
20
EXAM TIP Be sure to know the difference between the DataSource and
DataMember properties.
There are a few important characteristics of a DataGrid control that you should
know about. The first is that in order to format the display of data in a manner other
than the default display shown in Figure 20-14, you need to work with the properties of
PART III
the DataGrid, such as GridLineStyle, which can be set to Solid (the default) or
None. This can be done programmatically by creating a DataGridTableStyle object
and setting its properties to the display you need:
You can set the column style by using the DataGrid properties, or programmatically
by using a DataGridTextBoxColumn object:
You can also set properties such as Width, Alignment, HeaderText, and so on. Once
the desired properties have been set, you can then add the DataGridTextBoxColumn
to the GridColumnStyles collection as follows:
myStyle.GridColumnStyles.Add (myColumns);
Finally, you’ll need to add the table style to the data grid:
dataGrid1.TableStyles.Add (myStyle);
You can also use the AutoFormat tool to select a preset format for your DataGrid.
Right-click on the DataGrid on your form, and select AutoFormat. Figure 20-15 shows
the Auto Format dialog box that appears.
The DataGrid control can also be used to show the relationship between two re-
lated tables. Here’s what you would do:
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:21 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
20
If you wish to experiment with this process using the DataGrid, follow the preced-
ing steps. We will explore table relationships later in this chapter, and we’ll look at how
to relate them programmatically.
EXAM TIP To manually load data, you use the Fill() method of the
DataAdapter.
To produce the output that you saw in Figure 20-14 you need to load the data into the
DataSet by using the DataAdapter. Where in the application you do this is an im-
portant consideration. You don’t want to do it too early, because you will be wasting re-
sources before they are actually needed, and you don’t want to do it too late, because the
process may take some time. Take time to determine the appropriate time to access
the actual data.
For the purpose of demonstration only, we will add the following code to the load
event of the form:
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:21 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
20
PART III
will be creating the SQL code or using stored procedures. For this example, we will take
you through the steps of creating a new stored procedure; however, by selecting Use Ex-
isting Stored Procedures in that window, you can access code that has been created in
advance and stored on the database server.
To create a new stored procedure, select the Create New Stored Procedures option
and click Next. You will be taken through the steps of building a query as we saw in the
“ADO.NET Objects in Visual Studio .NET” section (Figures 20-9 and 20-10). Once your
SQL statements are created, you will be taken to the Create the Stored Procedures screen
(Figure 20-16).
Figure 20-16
The Create
the Stored
Procedures
screen of the
Data Adapter
Configuration
Wizard
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:21 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
20
What’s Next?
So far we have spent very little time coding. Although this is a very attractive feature of
the Visual Studio .NET environment, it may not necessarily provide you with the flexi-
bility that you need when creating data access. However, in this section, we have covered
the major topics that deal with ADO.NET objects in Visual Studio.
EXAM TIP What you have seen so far covers the extent to which Microsoft
will test you on Visual Studio ADO.NET objects. As any good programmer
knows, though, you should spend more time investigating the power of the
development environment and the many classes that have been built to assist
with data retrieval and presentation.
The remainder of this chapter will be devoted to programmatically retrieving and dis-
playing data. We will discuss such features as data bindings, formatting, and parsing
data. Our goal is to create the form that you see in Figure 20-18, which retrieves data
from the SQL Server and presents it in text boxes that have been bound to the data.
Figure 20-17
The Preview
window
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:22 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
20
PART III
Figure 20-18 The college application form
Data Binding
Just what is data binding? Obviously, as its name implies, it is the process of linking data
with something. In prior versions of Microsoft data-object models, you could “bind”
data to a control that had data source, data member, and data field properties. For exam-
ple, a text box could be programmed to contain data from an SQL Server data source, a
SELECT statement, and a particular field from the SELECT statement. Although this
technique is slightly different in .NET, there are many more possibilities with Windows
Forms using the .NET Framework.
The traditional data sources (such as a database) can be used, as well as any object that
implements data-binding interfaces—IList, IBindingList, or IEditableObject.
Fortunately, you do not need to know any of this for the Microsoft exams, but the possibil-
ities of this new approach are virtually endless. As an example, you can create a collection
of values at run time that can then be used to bind to any property of a control.
EXAM TIP For the C# Windows exam, be very aware of the fact that
you are not limited to binding to controls that traditionally had “bindable”
properties, such as DataSource. A Windows Form control can be bound
to virtually any data source. You also do not have to bind the data to a visual
property (like the Text property of a TextBox).
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:22 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
20
The .NET Framework allows you to use two different techniques for data binding:
In this section, we will look at the two different kinds of binding and at setting proper-
ties both at design time and run time.
EXAM TIP Microsoft will test you on your knowledge of data binding. Pay
particular attention in this section to binding programmatically to a data source.
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:22 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
20
Once you close the Advanced Data Binding dialog box, you can run the application
and see that the Student# field from the Student table is displayed in the correct text
PART III
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:23 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
20
box. You can do the same thing for all of the text boxes on the form to display all the in-
formation about the first student in the table (see Figure 20-21).
TIP If you don’t see the data, don’t forget that you must manually populate
the DataSet.
• DataSource: Choose the DataSet object that represents the table from
which the data will be extracted.
• DisplayMember: Select the field (or column) or data that should be
displayed.
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:23 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
20
PART III
Figure 20-21 Simple data binding
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:23 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
20
has been added to the form, and the user clicks that button to display the data (see Fig-
ure 20-23).
To link our data source and the actual control, you can instantiate a Binding object,
as shown here:
After the Binding object has been instantiated, you need to add it to the
DataBindings collection of the control (in this case, the TextBox control):
this.txtStudentNo.DataBindings.Add (StudentBinding);
You can save yourself programming space and typing by simply sending the Bind-
ing parameters to the Add() method of the DataBindings collection. The following
code listing demonstrates how to populate each of the text boxes on the form shown in
Figure 20-23.
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:24 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
20
EXAM TIP You do not always have to provide the table name as the third
parameter of the Add() method; however, it is necessary if you have more
than one DataTable object (such as a DataSet).
PART III
multiple rows of data, like the DataGrid. As we saw in the previous “Simple Binding
Figure 20-23 Displaying data dynamically using simple binding at run time
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:24 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
20
dgStudents.DataSource = dsStudent;
dgStudents.DataMember = "FirstName";
This code will cause the list box to display all records represented by the data source, but
only the FirstName column.
EXAM TIP You can also use the SetDataBinding method of the
DataGrid object to bind both the DataSource and DataMember
properties. A DataGrid is also considered a complex control in terms
of data binding.
Another thing you can do when displaying data is display a value that is related to
but different from the actual bound data. For example, you may wish to provide a
user-friendly display of a primary key. The actual primary key value may be an auto-
matically generated number that really means nothing except as a unique key. By using
the ValueMember property of some controls, you can display the name associated
with the primary key and still bind the primary key field for programmatic usage.
Property Explanation
Current Contains the value of the current item in the data source.
Position Returns the position of the current object in the data source.
List Returns the data source.
Bindings Returns the collection of bindings that the CurrencyManager manages.
Count Returns the number of rows that are being managed.
Table 20-2 Properties of the CurrencyManager
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:25 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
20
PART III
creates a new instance of the Binding object and adds it to the Bindings collection.
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:25 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
All-In-One
screen / MCAD/MCSD
/ MCSD Visual
Visual
C#C#
.NET
.NET
Certification
Certification
All-in-One
All-in-One
Exam
Exam
Guide
Guide
/ Rempel
/ Rempel
& Lind
& Lind
/ 222443-6
/ 222443-6
/ Chapter
/ Chapter
20
20
Exception Handling
Any application that accesses data needs the ability to prevent run-time errors from hap-
pening. Consider the following scenario. You design a Windows Form like the college
application, and the database server is in a remote location from the user of the Win-
dows Forms (which is a very typical arrangement). For some reason, the connection to
the database server fails. What happens to your application?
If you have followed good programming practices, nothing terminal should happen.
Obviously, the connection failure is a problem for the user, since the live connection to
the data is now disconnected. However, your application should not terminate with
some cryptic message generated by the internal exception-handling mechanism. In-
stead, you want to trap any exceptions and handle them properly. (Refer to Chapter 4
for the basics of exception handling.)
What you need to do is enclose your code in try … catch blocks to make sure that
any exceptions that are beyond your control are handled. As a reminder, here is what
happens with good exception-handling code:
EXAM TIP The finally block always executes (unless the power plug has
been pulled!).
The type of exceptions that can occur when working with data are shown in Table 20-3.
All exceptions found in ADO.NET have System.Data.DataException as their
base class.
Exception Explanation
ConstraintException This exception indicates that a constraint has been violated.
For example, a primary key record was deleted when foreign
key records still exist.
DataException This is the base class.
DBConcurrencyException This exception means database write conflicts have occurred.
For example, this could happen if one user is updating the
database while another is trying to.
Table 20-3 Classes Derived from System.Data.DataException
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:25 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
20
PART III
Although we have not tried to access data programmatically in our application so far,
the code section found in Figure 20-25 demonstrates good practice when connecting to
a database. The try block attempts to create the connection and “tests” it using a try
block. If the connection cannot be made, the catch block catches the exception.
Without this coding, we would receive the message shown in Figure 20-26, which
forces the user to ignore the message or quit the application. If the connection fails, the code
within the catch block executes (assuming an SqlException has been thrown).
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:26 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
20
Although we have done nothing exciting within the catch block in this example, in
a real-life scenario you would provide code that would either prompt the user for addi-
tional credentials, or prevent the user from accessing the database, or do whatever is
necessary to gracefully exit the error condition. Figures 20-27, 20-28, and 20-29 show
the sequence of events when an SqlException occurs in the code shown in Figure
20-25. Notice that the finally block is executed too.
In Figure 20-29, you can see that we used the exception object that is created
(SqlException s), and then we displayed its Message property to provide a
user-friendly message regarding the status of the exception.
EXAM TIP You can create your own data-access exceptions—be sure that
they inherit from System.Data.DataException.
Some of the properties of the exception object are listed in Table 20-4.
From this point on in our discussions about data, we will be following this conven-
tion of catching data exceptions and providing the coding to handle them.
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:26 PM
Color profile: Generic CMYK printer profile
All-In-One
Composite Default screen All-In-One
/ MCAD/MCSD
/ MCSD Visual
Visual
C#C#
.NET
.NET
Certification
Certification
All-in-One
All-in-One
Exam
Exam
Guide
Guide
/ Rempel
/ Rempel
& Lind
& Lind
/ 222443-6
/ 222443-6
/ Chapter
/ Chapter
20
20
Figure 20-28
The try block—
using the
exception object
PART III
Figure 20-29
The finally
block
Description
HelpLink Provides a link to a help file giving more information about the exception.
InnerException Contains the exception object that caused the code to enter the catch
block. This is used if the exception happened inside a catch block.
Message Provides a text message to give more information about the exception
to the user.
Source Provides the name of the object that caused the exception.
StackTrace Provides a means of viewing the call stack (the list of methods in
execution order).
Table 20-4 Properties of the Exception Object
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:26 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
20
EXAM TIP The SqlConnection class is used for accessing Microsoft SQL
Server 7 (and higher). To access an earlier version of SQL Server, you will
need to use a different data source provider class.
When you instantiate an SqlConnection object, you must provide the connection
parameters to the constructor. The best way to handle this is to create a string object first,
and then pass the string object to the SqlConnection constructor, like this:
The connection string is very similar to those for the ADO or OLE-DB providers in ver-
sion 6 of Visual C++ or Visual Basic. It consists of three components:
• data source—the server location of the database. If the server was located
somewhere other than on the client, the entry would be something like this:
"data source=\\SQLServer"
• initial catalog—the name of the database.
• user id and password—the log in credentials.
You could specify integrated security instead of providing the userid and password
within the connection string. In that case, you would code "integrated security".
The connection object can be thought of as the bridge between your application and
a data provider. Connection strings vary slightly depending on the data provider
(OLE-DB, ODBC, and so on). Once the string is created, you then pass it to the connection
constructor as follows:
By using this method, you can modify the connection string at any time without touch-
ing the actual creation of the connection object.
All that’s left to do now is to open the connection, which, essentially, provides us
with a link to the data source. No command is being run against the data in the follow-
ing code, no data is transferred—this simply creates a pipeline to the data.
try
{
MyConnection.Open();
}
catch
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:26 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
20
Be sure to close the connection when you are finished with it. The garbage collector can
then destroy the object and free the memory space:
try
{
MyConnection.Close();
}
catch
{ … Etc…
PART III
Creating a Command Object
The next step is to create the object that encapsulates the code that you want executed on
the data source. This could be a stored procedure on the database server or a configured
SQL statement located in your code. Either way, you need a Command object to do this
for you. The command object will use the connection object to access the database (or it
can provide its own connection data). Once the command is executed against the data
source, the data is returned to the user in the form of a stream (read by DataReader ob-
jects) or a DataSet object. The following code is used to instantiate a command object:
You can also use the connection object to create the command object. The connection
object has a CreateCommand() method that you can use to instantiate your com-
mand object.
Once the command object is created, you can use the execute methods associated
with an SqlCommand object:
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:27 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
All-In-One
screen / MCAD/MCSD
/ MCSD Visual
Visual
C#C#
.NET
.NET
Certification
Certification
All-in-One
All-in-One
Exam
Exam
Guide
Guide
/ Rempel
/ Rempel
& Lind
& Lind
/ 222443-6
/ 222443-6
/ Chapter
/ Chapter
20
20
Figure 20-30 shows code that instantiates and uses a command object.
We can then use this data adapter to create the DataSet object that will be a copy of the
actual data retrieved through the command object:
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:27 PM
Color profile: Generic CMYK printer profile
All-In-One
Composite Default screen All-In-One
/ MCAD/MCSD
/ MCSD Visual
Visual
C#C#
.NET
.NET
Certification
Certification
All-in-One
All-in-One
Exam
Exam
Guide
Guide
/ Rempel
/ Rempel
& Lind
& Lind
/ 222443-6
/ 222443-6
/ Chapter
/ Chapter
20
20
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
namespace WindowsApplication2
{
public class Form1 : System.Windows.Forms.Form
{
PART III
private System.Windows.Forms.Button button1;
protected SqlConnection studentConnection;
protected SqlCommand studentCommand;
protected SqlDataAdapter studentAdapter;
protected DataSet studentSet;
private System.Windows.Forms.Button btnGetData;
private System.Windows.Forms.TextBox txtFirstName;
private System.ComponentModel.Container components = null;
public Form1()
{
InitializeComponent();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void InitializeComponent()
{
this.btnGetData = new System.Windows.Forms.Button();
this.txtFirstName = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// btnGetData
//
this.btnGetData.Location = new System.Drawing.Point(97, 124);
this.btnGetData.Name = "btnGetData";
this.btnGetData.TabIndex = 0;
this.btnGetData.Text = "GetData";
this.btnGetData.Click += new System.EventHandler(this.btnGetData_Click_1);
//
// txtFirstName
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:27 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
20
DataReader
If you are looking for an object that will give you a fast and efficient return of rows of
data, the DataReader is the object for you. This object provides a stream of rows in a
forward-only cursor. There is no opportunity to move forward and backward through
the data, and you cannot search for records. However, if you need to quickly scroll
through data, the DataReader is what you want. You can create a DataReader from
the command object:
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:27 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
20
PART III
to transform and filter data. To that end, we will explore two techniques—formatting and
parsing. The Binding object exposes two events—Format and Parse. We will discuss
these two events in the next two sections.
• When the data is bound for the first time to the control
• When the Position property changes (refer back in this chapter for the
Position property—it is used to reposition the row indicator)
• When the data is sorted or filtered
Of course, you still need to code the yourFormatName method; but the preceding
code adds the handler to the Binding object in the text box’s DataBindings collection.
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:27 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
20
You can use code similar to what we showed for the Format event:
EXAM TIP The Format event is triggered when the data is bound to
the control, when the Position changes, or when the data is sorted or
filtered. The Parse event is triggered after a Validation event, when the
Position changes, or when the EndCurrentEdit() method is called.
Summary
This chapter has covered the exam objectives related to data access in Windows Forms.
You should pay particular attention to the sections that deal with binding data to controls
(both simple and complex binding) as well as the ADO.NET objects used for retrieving
data from a data store (Connection, Command, DataSet, and DataAdapter).
Microsoft will also test your understanding of the various data providers (SQL,
OLE-DB) and when they are used—remember that the SQL provider is used for versions
of Microsoft SQL Server 7.0 and higher.
In order to feel very comfortable with the concepts presented in this chapter, you
should find an evaluation copy of Microsoft SQL Server 2000 and set up a simple data-
base (as we have done with the College database). Test yourself by creating connections
and commands and displaying the data. That is the one way to make sure that you are
ready for Microsoft’s exam.
Test Questions
1. Which code segment will populate a DataSet?
A. sqlDataProvider1.Fill (dsUsers1);
B. sqlDataProvider.Fill (dataAdapter1);
C. sqlDataAdapter.Fill (dsUsers1);
D. sqlDataAdapter.Fill (dataAdapter1);
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:28 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
20
PART III
4. You need to get access to a database that is stored on a server running
Microsoft Access 2002. Which data adapter would you use?
A. SqlDataAdapter
B. OleDbDataAdapter
C. OleDataAdapter
D. ODBCDataAdapter
5. You need to get access to a database that is stored on a server running
Microsoft SQL Server 2000. Which data adapter would you use?
A. SqlDataAdapter
B. OleDbDataAdapter
C. OleDataAdapter
D. ODBCDataAdapter
6. You want to return XML data from a Microsoft SQL Server 7.0 database.
Which method would you execute?
A. ExecuteXmlReader()
B. ExecuteXmlData()
C. ExecuteOleReader()
D. ExecuteOldData()
7. The Parse event is triggered after which of these occurrences?
A. Data is sorted.
B. Data is filtered.
C. Data is bound to a control.
D. Data is returned to the data source.
E. All of the above.
F. None of the above.
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:28 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
20
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:28 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
20
PART III
11. You are the consultant for HMR Inc. They have a large network that includes
a Microsoft SQL Server 2000 database. You have coded a connection and
command object to retrieve data from the Student database, but you keep
getting an exception. What is wrong with the following code?
try
{
studentConnection.Open();
studentCommand = studentConnection.CreateCommand();
studentCommand.CommandType = CommandType.Text;
studentCommand.CommandText = "SELECT * FROM Student";
studentAdapter = new OleDbDataAdapter (studentCommand);
studentSet = new DataSet();
studentAdapter.Fill (studentSet, "FirstName");
this.txtFirstName.DataBindings.Add ("Text", studentSet, "FirstName");
}
catch (OleDbException s)
{
MessageBox.Show ("Oops, something bad happened");
}
finally
{
studentConnection.Close();
studentConnection = null;
}
}
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:28 PM
Color profile: Generic CMYK printer profile
Composite Default All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
20
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:28 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
20
Test Answers
1. C.
2. C.
3. D.
4. B.
PART III
5. A.
6. A.
7. D.
8. E.
9. B. The command type is Text not StoredProcedure.
10. B. The exception is caused by the column named Name.
11. F.
12. C.
13. A.
14. D.
15. B. (Well, it could be D!!)
P:\010Comp\All-in-1\443-6\ch20.vp
Friday, August 23, 2002 5:03:28 PM