Windows Forms Controls and Data Binding


Windows Forms Controls and Data Binding

Many properties of most Windows Forms controls can be attached, or bound, to a data source. After they are bound, the value in the data source changes the value of the bound property and vice versa. You have already seen data binding in action by using the TextBox and DataGridView controls in the DisplayProducts project in Chapter 23. The controls on the form were bound to BindingSource objects belonging to a DataSet containing records from the Suppliers and Products table in the database.

Windows Forms controls support two types of data binding: simple and complex. Simple data binding allows you to attach a property of a control or form to a single value in a data source, and complex data binding is specifically used to attach a control to a list of values. Simple data binding is useful for controls such as TextBox or Label that only display a single value. Complex data binding is more commonly used with controls that can display multiple values, such as ListBox, ComboBox, or DataGridView.

Defining a DataSet and Using Simple Data Binding

You use simple data binding to display a single value from a data source. A data source can be almost anything, from a cell in a DataSet to the value of a property of another control to a simple variable. You can perform simple data binding at design time by using the Data-Bindings property of a control. In the exercises that follow, you will define a new DataSet that defines a data source returning a single row, and then bind the Text property of a Label control to a BindingSource object for this DataSet.

Defining a DataSet class

  1. In Visual Studio 2005, create a new project called ProductsMaintenance in the \Microsoft Press\Visual CSharp Step by Step\Chapter 24 folder in your My Documents folder by using the Windows Application template.

  2. In the Project menu, click Add New Item.

    The Add New Item dialog box appears, displaying templates for objects that can be added to a project.

    graphic

  3. In the Add New Item dialog box, click the DataSet template, type NorthwindDataSet.xsd for the name, and then click Add.

    NOTE
    DataSet definitions should always be created in a file with the extension “.xsd.” DataSet definitions are actually XML schemas, which Visual Studio 2005 uses to generate C# code when the application is built.

    The DataSet Designer window appears.

    graphic

  4. In the Toolbox, expand the DataSet category if necessary, and then click the TableAdapter tool. Click anywhere in the DataSet Designer window.

    A DataTable and TableAdapter object are added to the DataSet Designer window, and the TableAdapter Configuration Wizard appears.

    graphic

  5. In the Choose Your Data Connection page of the TableAdapter Configuration Wizard, click Next.

    NOTE
    The Choose Your Data Connection page in the TableAdapter Configuration Wizard will either display NorthwindConnectionString or YourServer\sqlexpress.Northwind.dbo for the data connection, depending on whether you have left Visual Studio 2005 running since performing the exercises in Chapter 23, or have closed it down and restarted it. Either data connection will work for this exercise.

  6. If the “Save the connection string to the application configuration file” page appears, specify that the connection string should be saved with the name NorthwindConnectionString and click Next.

    The Choose a Command Type page appears.

  7. The “Choose a Command Type” prompts you to specify how the TableAdapter should access the database. You can provide your own SQL statements, you can get the Wizard to generate stored procedures that encapsulate SQL statements for you, or you can use pre-existing stored procedures that a database developer has already created. Select Use SQL statements, and then click Next.

    graphic

    The Enter a SQL Statement page appears.

  8. Type the following SQL SELECT statement that calculates the number of rows in the Products table:

    SELECT COUNT(*) AS NumProducts FROM Products

  9. Click Advanced Options.

    The Advanced Options dialog box appears.

    graphic

    Apart from retrieving data from the database, a TableAdapter object can also insert, update, and delete rows. The Wizard will generate SQL INSERT, UPDATE, and DELETE statements automatically, using the table you specified in the SQL SELECT statement (Products in this example).

  10. The SQL SELECT statement used to fetch data simply counts the number of rows in the Products table. It does not make sense to generate SQL INSERT, UPDATE, or DELETE statements as this value is not directly updateable. Clear the “Generate Insert, Update, and Delete statements” check box and then click OK.

  11. In the Table Adapter Configuration Wizard, click Next.

    The “Choose Methods to Generate” dialog box appears.

  12. A TableAdapter can generate two methods for populating a DataTable object with the rows retrieved from the database: the Fill method which expects an existing DataTable or DataSet as a parameter which is filled with the data, and the GetData method which creates a new DataTable and fills it. Leave both methods selected, and then click Next.

  13. The Wizard uses the information you have supplied and generates the new TableAdapter class. Click Finish to close the Wizard.

    A TableAdapter class called DataTable1TableAdapter, and a corresponding DataTable class called DataTable1, appear in the DataSet Designer window.

  14. In the DataSet Designer window, click the DataTable1 item. Using the Properties window, change its Name property to NumProductsTable. Click the DataTable1TableAdapter and change its name to NumProductsTableTableAdapter. The objects in the DataSet Designer window should look like the following graphic:

    graphic

    Notice that NumProductsTable DataTable contains a single column called NumProducts. This column is filled with the value of the NumProducts expression (the number of rows in the Products table), when the underlying SQL SELECT statement runs.

  15. On the Build menu, click Build Solution.

    This action generates the the code and objects for the DataSet, so that they can be used in the next exercise.

TIP
You can view the code that is generated by Visual Studio 2005 by expanding NorthwindDataSet.xsd in the Solution Explorer, and double-clicking the file NorthwindDataSet. Designer.cs that appears. Be careful not to change any of this code, however.

In the next exercise, you will bind to the value retrieved by the NumProductsTableAdapter from the database into the NumProducts DataTable in the NorthwindDataSet DataSet to the Text property of a Label control. When the application runs, the label will display the number of rows in the Products table.

Bind to a column in a DataTable

  1. Display Form1 in the Design View window. In the Solution Explorer, change the filename from Form1.cs to ProductsForm.cs. When prompted, click Yes to rename all references to Form1 in the project.

  2. Using the Properties window, change the Text property to Products Maintenance.

  3. Add a Label control to the form. Change the Text property of the control to Number of Products:, and set its Location property to 25, 34.

  4. Add another Label control to the form. Set the Location property of the control to 131, 34, and change its (Name) property and Text property to numProducts.

  5. Expand the (DataBindings) property for the numProducts label. Click the Text property (inside DataBindings), and then click the drop-down menu that appears.

    A window appears displaying a tree view of data sources. Expand the Other Data Sources node, expand Project Data Sources, expand NorthwindDataSet, expand NumProductsTable, and then click NumProducts. This action binds the Text property of the Label control to the NumProducts column in the NumProductsTable DataTable.

    graphic

    Visual Studio 2005 generates an instance of the NorthwindDataSet class called northwindDataSet, an instance of the NumProductsTableAdapter class called numProductsTableAdapter, and a BindingSource object called numProductsTableBindingSource, and adds them to the form.

  6. Click the numProductsTableBindingSource object underneath the form. Using the Properties window, click the DataSource property. This property identifies the DataSet object that the BindingSource uses to connect to the database; notice that it refers to northwindDataSet.

  7. Click the DataMember property. This property specifies the DataTable object in northwindDataSet that acts as the source of the data; it is set to NumProductsTable.

  8. Click the numProducts label again, and expand the (DataBindings) property. Examine the Text property again, and notice that it is set to numProductsTableBindingSource – NumProducts.

  9. View ProductsForm.cs in the Code and Text Editor window and locate the ProductsForm_Load method.

    This method, which was generated by Visual Studio 2005, runs when the form opens. It contains the following statement:

    this.numProductsTableAdapter.Fill(this.northwindDataSet.NumProductsTable);

    From this set of objects, properties, and the code, you should be able to deduce how label2 gets its data from the database:

    1. The numProductsTableAdapter object connects to the database and retrieves the number of rows in the Products in the database by executing its SQL SELECT statement.

    2. The numProductsTableAdapter uses this information to fill the NumProductsTable DataTable object in the northwindDataSet object when the form starts.

    3. The numProductsTableBindingSource object connects the NumProducts column in the NumProductsTable DataTable object in the northwindDataSet object to the Text property of label2.

  10. Build and run the application.

    The Label control displays the number of rows in the Products table (probably 77 if you have not changed any of the data since the database was created).

  11. Close the form and return to the Visual Studio 2005 programming environment.

Dynamic Data Binding

You can set the DataBindings property of a control by using code which executes at runtime as well as setting it statically at design time. The DataBindings property provides the Add method that you can use to bind a property to a data source. For example, you can bind the Text property of a Label control called myLabel to the NumProducts column in numProductsTableBindingSource like this:

myLabel.DataBindings.Add("Text", numProductsTableBindingSource, "NumProducts");

The parameters to the Add method are the name of the property to bind to, the name of an object containing the data to be bound to, and the member actually providing the data.

You can use the Add method to bind to properties of other controls. The following example binds the Text property of myLabel to the Text property of a TextBox control called myText:

myLabel.DataBindings.Add("Text", myText, "Text");

If you try this code, you will find that the Label automatically updates itself as you type text into the TextBox.

Using Complex Data Binding

You have seen how to use simple data binding for attaching the property of a control to a single value in a data source. Complex data binding is useful if you want to display a list of values from a data source. In the following exercises, you will use complex data binding to display the names of suppliers from the database in a ComboBox control and then display the SupplierID of a supplier that the user selects. You will make use of the techniques you learn here when enhancing the Products Maintenance application later in this chapter.

TIP
The ListBox and CheckedListBox controls also support complex data binding by using the same techniques that you will see in these exercises.

Create and configure the data source

  1. In the Solution Explorer, double-click NorthwindDataSet.xsd to display the DataSet Designer window.

  2. Using the Toolbox, add another TableAdapter to the DataSet.

    The TableAdapter Configuration Wizard opens.

  3. In the TableAdapter Configuration Wizard, use the NorthwindConnectionString to connect to the database and click Next.

  4. In the Choose a Command Type page, select Use SQL statements and click Next.

  5. In the Enter a SQL Statement page, click Query Builder.

    The Query Builder dialog box opens.This wizard provides a convenient way for constructing SELECT statements if you cannot remember the syntax of SQL.

  6. In the Add Table dialog box, select the Suppliers table, click Add, and then click Close.

    The Suppliers table is added to the Query Builder dialog box.

  7. Check the SupplierID and CompanyName column. Notice that the lower pane in the dialog box displays the SQL SELECT statement that corresponds to the columns you have selected:

    SELECT SupplierID, CompanyName   FROM Suppliers

    You can verify that this statement retrieves the rows you are expecting by clicking the Execute Query button. The results of the query are displayed in the pane at the bottom of the dialog box.

    graphic

  8. Click OK to close the Query Builder and return to the TableAdapter Configuration Wizard.

    The SELECT statement is copied into the Enter a SQL Statement page.

  9. This application will not actually change the details of any supplier, so click Advanced Options and deselect Generate Insert, Update and Delete statements. Click OK, and then click Finish.

    A new DataTable class called Suppliers, and a DataTableAdapter class called SuppliersTableAdapter, are added to the DataSet Designer window.

  10. Rebuild the solution to generate the code for the new objects.

Bind a ComboBox to the DataTable

  1. Display ProductsForm in the Design View window.

  2. Using the Toolbox, add a ComboBox control and a Label to the form. Set the properties of these controls by using the values in the following table.

    Control

    Property

    Value

    comboBox1

    (Name)

    supplierList

    Location

    25, 65

    label2

    (Name)

    supplierID

    Location

    178, 70

    Text

    SupplierID

  3. Click the ComboBox control on the form. In the Properties window, click the DataSource property. Click the drop-down menu that appears. Expand Other Data Sources, expand Project Data Sources, expand NorthwindDataSet, and click Suppliers.

    This action binds the ComboBox control to the Suppliers DataTable, and generates a new BindingSource control called suppliersBindingSource and an instance of the SuppliersTableAdapter class, and adds them to the form.

  4. While the ComboBox is still selected, set its DisplayMember property to CompanyName, and set its ValueMember property to SupplierID.

    When the form runs, it will display a list of suppliers in the combo box. When the user selects a supplier, its SupplierID will be available as the combo box value.

  5. Click the Events button in the Properties window and double-click the SelectedIndexChanged event for the ComboBox.

    The code for ProductForm is displayed in the Code and Text Editor window, and a click event handler called supplierList_ SelectedIndexChanged is generated.

  6. Add the following statements to the supplierList_ SelectedIndexChanged method:

    if (supplierList.SelectedValue != null) {      supplierID.Text = supplierList.SelectedValue.ToString(); }

    This block of code displays the ID of the supplier the user selects in the supplierID label. The SelectedValue property returns the ValueMember of the currently selected row. It is returned as an object, so you must use ToString if you want to treat it as a string.

  7. Examine the ProductsForm_Load method. Notice that another line of code has been generated that populates the Suppliers DataTable in the northwindDataSet object by using the Fill method of suppliersTableAdapter.

  8. Build and run the application. The combo box displays the names of all suppliers. Click a supplier. The ID appears in the label to the right of the combo box. Click other supplier names and verify that the ID displayed is updated appropriately.

  9. Close the form and return to Visual Studio 2005.




Microsoft Visual C# 2005 Step by Step
Microsoft® Visual C#® 2005 Step by Step (Step By Step (Microsoft))
ISBN: B002CKYPPM
EAN: N/A
Year: 2005
Pages: 183
Authors: John Sharp

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net