Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Microsoft CSharp Programming For The Absolute Beginner (2002) [eng]-1.pdf
Скачиваний:
46
Добавлен:
16.08.2013
Размер:
15.71 Mб
Скачать

Figure 11.10: Agents table after I’ve entered a few of my agents. (This page will self−destruct in 5 seconds…)

Keeping Track of Your Data Structure

The way the server explorer displays the structure of your database in the IDE is a welcome addition. You used to be able to tell which programmers were working on databases because they always had paper diagrams of their data structure tacked to all the walls in their cubicle. (Many pros still do this.) In fact, there are stories of data programmers taking only their data diagrams as they left a burning building. The problem with paper diagrams is they have to be replaced every time the data structure is changed. The server explorer gives you an easy way to see exactly what tables are in your database, and what fields belong to each table. This seems like trivial information to keep track of right now, but the complexity of databases seems to grow very quickly.

Accessing the Data in a Program

Now the spy data is available to my server, but it isn’t very interesting there. I want to be able to use the data in programs to save the world for democracy, apple pie, and quarter video arcades. It shouldn’t surprise you that the IDE makes it easy to integrate a database with a program. Once you’ve created a database on your server, you can easily access it from any programs written on that same machine (later on I’ll show you how to get to other databases, too). To illustrate this, create a project (or simply go to a form if you’re already in a project). C# has a special control designed explicitly for working with databases. It’s called the Data Grid control. To use it, display a form in the visual designer, and go back to the traditional toolbox (with all the form components you’re used to placing on the screen). The data grid can be dropped on the form like any other control. It is not very interesting unless it is connected with some form of database. To begin creating the data connection, drag the Agents table from the server connection onto your form. Figure 11.11 illustrates the visual designer after I have added a data grid control and dragged the Agents table to the form.

326

Figure 11.11: When you drag a table to your form, two new objects are created in the non−visible segment of your form.

Dragging a table to the form causes the IDE to create two objects. A SqlConnection object describes the connection between your program and the database. There are other kinds of connection objects, but they all do basically the same thing. A connection object encapsulates the actual connection. If you want to connect to a database on a remote system, you can set up the connection object to point to the remote machine, handle any logins, and start the connection.

The most critical property of the SqlConnection is the ConnectionString property. Take a look at it in the designer; it’s a big ugly string variable designed to specify how to connect to the database. It’s usually easiest to let the designer automatically generate an SqlConnection object, (and the complicated ConnectionnString property) and then modify it as needed.

The other object that is automatically created when you drag a table to the screen is an instance of SqlDataAdapter. The adapter classes are a new feature of the .NET data access scheme. In a nutshell, a data adapter automatically generates a local copy of a database on the client’s computer, and manages the relationship between the local copy of the database and the original database. This separation is especially useful when you are working on databases across Internet connections, but it works just as well when the database is local. You’ll generally work with the SqlDataAdapter’s Fill() method when you want to request data from the main database, and the Update() method when you want to update the main database from your local version.

Creating a DataSet Object

Although the SqlConnection and SqlDataAdapter are handy, you need one more data class to work directly with data in your forms. This important class is called the DataSet class. Each database uses a custom extension of the DataSet class to provide access to the database. Fortunately, .NET makes it easy to generate an appropriate DataSet from a data adapter. To create the new DataSet, look at the properties box of the DataAdapter class. At the bottom of the properties box, you see links for some special commands. Choose Preview Data, and you see the dialog box featured in Figure 11.12.

327

Figure 11.12: The Preview Data dialog illustrates how the data looks to the program.

How Do Data Connections, Data Adapters, and Data Sets Fit Together?

All this new (and similar) terminology can be baffling. It actually makes sense if you understand how Microsoft’s underlying data model (called ADO.NET) works. Essentially, your programs are considered completely separated from your actual database, even if they are on the same machine. In the .NET model, databases and programs have the same kind of long−distance relationship that Web browsers have with Web servers. In the Web, a browser requests a page, and that page is loaded onto the local machine. The ADO.NET data model works in a very similar way. Think of the DataConnection object as being your placeholder for the actual (remote) database. The DataSet object holds a local copy of the data. You can manipulate the DataSet object all you want, but it doesn’t directly affect the original database. The DataAdapter class is the conduit between the (remote) DataConnection and the (local) DataSet. The DataAdapter reminds me of the pneumatic tubes sometimes used at bank drive−through windows to send checks and pens from the bank to the cars. It is a communication medium. You use methods of the DataAdapter to fill up the DataSet with data from the DataConnection, and you use other methods of DataAdapter to update the original database from the local DataSet. If you’re still confused, read on. You’ll get it after a little more exposure.

The Preview Dialog creates a temporary DataSet based on a particular data adapter. Because the

328

current program has only one data adapter available, clicking on the Fill DataSet button creates the temporary data set based on the current data adapter, and displays the results in the dialog, as illustrated in Figure 11.13.

Figure 11.13: After pressing the Fill DataSet button, the data set appears on the dialog.

Once you have confirmed that the database acts as you expect, close the Preview Data dialog and look again at the bottom of the Properties Window for the Generate DataSet command. Click on this link to get the Generate DataSet dialog, shown in Figure 11.14.

329

Figure 11.14: The Generate DataSet Dialog prompts you to name your new DataSet.

To create a new DataSet, choose the New radio button, then type in the name of your new data set class.

Trap When you created the connection and adapter classes, you were making instances of existing classes. The data set is different, because you are creating an entirely new class that extends the base DataSet class. The Generate DataSet dialog creates both the new data set class and an instance of that class. That’s why when you leave the dialog, the data set object at the bottom of your form has a one at the end (the default name for any instance of a class is the class name followed by an integer). If you do not rename the data set, it is called DataSet1, and its first instance is called DataSet11. I was quite confused by this until I followed my own advice from way back in Chapter 1, "Basic Input and Output: A Mini Adventure." When you make new things, you should rename them. As you can see in Figure 11.14. I called my data set theData.

Once you leave the Generate DataSet dialog, you are returned to your form and a new instance of your data set appears at the bottom of the form near the connection and adapter objects. Because I named my data set theData, the default name for the new data set is theData1. I renamed the instance myDS, to help me remember this is my custom data set.

330

Connecting the Data Set to the Grid

The data grid control is designed to be bound to a data set. This allows an automatic connection between the grid and the data set. To bind myDS to the data grid, set the DataSource property of the grid to myDS, and the DataMember property to Agents. Both properties generate drop−down list boxes if the data source has been connected properly. Figure 11.15 illustrates setting up a data grid.

Figure 11.15: Setting the data DataMember property only works after you’ve set the DataSource property.

The DataSource property determines what DataSet object the grid will be connected to. DataSets can (and will, later in this chapter) have more than one table, so the DataMembers property is used to determine which table (or other entity) is connected to the grid.

Filling the DataSet from the Adapter

The database is almost ready. Figure 11.16 shows the data grid with its DataSource and DataMember properties set appropriately.

331

Figure 11.16: The program is almost ready, but the actual data has not yet been passed to the data set from the original database.

The only thing left to do is fill up the data set. Recall that the data set is simply a local copy of the database. The DataAdapter handles the connection between the original database and the copy stored in the data set. I added one line of code to the form’s load method to fill up the data set.

private void SimpleSpyForm_Load(object sender, System.EventArgs e) {

myAdapter.Fill(myDS); } // end form load

The adapter’s Fill() method requires a data set as a parameter. It goes to the original database and grabs the relevant information (determined by the properties of the adapter class) to populate the data set.

You can now run the Simple Spy program to get the results shown in Figure 11.17.

332

Соседние файлы в предмете Программирование на C++