Binding with Typed DataSets

As you saw in Chapter 20, "Strongly Typed DataSets," typed datasets are a feature provided by ADO.NET. They work by taking a schema that defines a set of relational data (tables, columns, foreign/primary keys, and so on) and turning that schema into a set of nested classes usable from within your application. Providing relational data exposed as a set of classes with strongly typed properties is a huge benefit to programmers working with relational data coming from any number of data sources including SQL Server or XML.

Using the Data Sources Window

When you're dealing with data-driven applications, the Data Sources window is probably one of the most powerful new features provided by the new Visual Studio. To get started, create a new Windows Application in C# (it doesn't matter what you call it). While looking at your main form, you may see a docked window called "Data Sources." If you don't, simply click the Data menu and then click Show Data Sources. You can also use the shortcut Shift+Alt+D. A sample of the Data Sources window is shown in Figure 37.1.

Figure 37.1. The Data Sources window.

This particular window shows that there are two data sources defined, both of them typed datasets. From this window, you can create new data sources as well as edit datasets with the designer or configure datasets with the Data Source Configuration Wizard as discussed in Chapter 20.

The Data Sources window shows all of the data sources configured for the current project. This means that if you have a typed DataSet, an Object DataSource, data obtained from SQL Server, or data obtained from an Access or OLE DB source, they will all show up in the Data Sources window. As you will find out later in this chapter, binding controls to data sources in this window is as easy as drag and drop.

Adding a DataSet to a Form

In previous versions of the .NET Framework, typed datasets were things that you could create on your own, and you could store them in your solution, but that was the extent of the built-in support. With Visual Studio 2005, typed datasets are an integral part of data binding.

To see how simple this really is, just create a new DataSet in your project. You can do this either through the Data Source Wizard in the Data Sources window, or you can right-click the project in Solution Explorer, choose Add Item, and select DataSet from the item templates list.

After your DataSet is configured to your liking, take a look at the Data Sources window. You will see that the typed DataSet you just created is listed there as a data source. Using the tree view, you can expand tables and columns and view the relevant properties of each aspect of the DataSet. If you highlight a DataSet in this window and click the Edit in Designer button, you will be taken to the dataset designer.

This sample contains a DataSet called ContactsDataSet with a single table called Contacts. This table has three columns: FirstName, LastName, and ID. The ID column is an AutoIncrement column that is also the primary key of the table.

Now all you have to do is open the Data Sources window and drag your newly created DataSet onto your form. When you let go of the mouse button, you will see that the following components have been added to the form:

  • Your typed DataSet (in my case this was ContactsDataSet)The typed DataSet actually appears at the bottom of the designer in the component tray as a full-fledged component.

  • A BindingSource component

  • A BindingNavigator component

  • A DataGridView control

The BindingSource component is new to .NET 2.0 and provides a level of abstraction and encapsulation around the data source for a form. What this means is that the methods of the BindingSource component work the same regardless of where the underlying data is physically stored or how it is stored. It also publishes a set of events that allow the developer to hook into actions such as when a new item is added, when the current item is changed, and so on.

The BindingNavigator sits on top of a BindingSource and allows navigation through the items in the underlying source data. It contains the User Interface elements that are typically used in navigating a source of data including controls to move to the beginning of the source, move to the end, move to the next item, and move to the previous item, create a new item, delete the existing item, and save the current data.

As you can see, the task of setting up a typed DataSet to be bound on a form is really as simple as dragging and dropping. With a few clicks you have a form that can add, delete, and edit records within your own typed DataSet. Figure 37.2 shows an example of a form created with this simple drag-and-drop procedure. In Figure 37.2, I deleted the DataGridView and dragged two columns onto the form from the Data Sources window. These columns arrive on the form prebound to the underlying data.

Figure 37.2. The result of dragging a DataSet onto a form.

It is worth mentioning here that so far what you have created is a form that is manipulating the contents of an in-memory DataSet. Keep reading to find out how to store the contents of the UI-bound DataSet in a backing store such as SQL Server or Oracle.

Typed DataSet Binding Sample

The preceding section showed you that in a matter of seconds, you can drag a DataSet from your Data Sources window and onto a form designer and have something that both runs and compiles. However, something like this isn't very practical and will never appear like this in an application unmodified.

What you'll see in this section is how to take the ContactsDataSet from the preceding drag-and-drop example and create an application that reads and writes data from an XML file.

To start, create a new Windows Application called TypedDSBinding. Rename Form1.cs to mainForm.cs. Now add the ContactsDataSet to the project. You can either copy it from previous samples if you were following along, or just create the DataSet manually with a single table called Contacts and the three columns: ID, FirstName, and LastName.

Now just drag the Contacts table from your Data Sources window onto the blank main form. As you've seen already, a DataGridView, a BindingSource, and a BindingNavigator will all appear on your form. Delete the DataGridView and then drag the FirstName and LastName columns onto the form. Thankfully, the painfully slow work of creating a TextBox, creating a Label, and then binding them up is all done for you when you drag columns onto a form.

The first piece of code you're going to want to write is the code to load the data into your DataSet from the XML file. Double-click the main form to create a Form_Load event handler and enter the following code:

private void mainForm_Load(object sender, EventArgs e) {     if (File.Exists(@"..\..\Contacts.xml"))     {         contactsDataSet.ReadXml(@"..\..\Contacts.xml");     } } 

Now you need to be able to save the list of contacts to disk when you're done. The first step is to single-click the button in the ToolStrip with the icon of a floppy disk. By default the Save button is disabled. Enable it, and then create a handler for the Click event as shown in the following code:

private void bindingNavigatorSaveItem_Click(object sender, EventArgs e) {     contactsDataSet.AcceptChanges();     contactsDataSet.WriteXml(@"..\..\Contacts.xml"); } 

Now when you run the application you will be able to create new contacts and edit existing ones, as well as delete contacts, and you didn't have to write any complex codejust a few lines of code to load and save a DataSet as an XML file.

Binding Caveats

One issue you may run into while working with automatically bound controls is that at times data you entered may seem as though it disappeared. This often happens when the data from the control is pushed back to the BindingSource. The changes from a control are only pushed to the BindingSource when the control's value changes. For most controls, the value doesn't technically change until the control loses focus. This means that for a value to "stick," you have to tab out of that control.

When you add new rows to a BindingSource, the row isn't actually going to be inserted until you move the current position off that row. This means that to add a new row, you need to add the row, enter the data, and then move back to a different record.

One way to make your UI work more intuitively in these scenarios is when the user clicks the Save button, you can programmatically tab them out of the current control and then manually commit the current row before saving by using a method like EndEdit on the BindingSource.

Microsoft Visual C# 2005 Unleashed
Microsoft Visual C# 2005 Unleashed
ISBN: 0672327767
EAN: 2147483647
Year: 2004
Pages: 298 © 2008-2017.
If you may any questions please contact us: