14.8 Databinding Windows Form Controls

 <  Day Day Up  >  

You want to use values from a database as values for certain properties of Windows Form controls.


Technique

Databinding a Windows Form control utilizes a separate approach than that taken by a DataGrid and ASP.NET controls. Rather than use a DataSource property and set a specific property for the display value, you create a data binding, which establishes a connection between the control and the underlying data source using a BindingContext .

The following example demonstrates creating a Windows Form application that creates a data binding between the text within a TextBox and the ProductName field within the Products table in the Northwind database. Furthermore, it demonstrates how to use the BindingContext object to easily navigate the records of the table to update the text displayed in the TextBox , as shown in Figure 14.1.

Figure 14.1. Navigating records using a BindingContext .

graphics/14fig01.gif

The application contains a single TextBox named tbName and two buttons named btnPrev and btnNext , which you use to select the previous or next record in the table, respectively. To databind a control, expand the DataBindings property item within the control's properties list. You see a list of possible properties that can be bound to. This example uses the Text property. Assuming you created the SqlConnection , SqlDataAdapter , and a typed DataSet , set the Text data-binding property to the ProductName field of the Products table defined in the DataSet . To display the text when the application starts, ensure that you call the Fill method defined in the SqlDataAdapter class, passing the DataSet as a parameter to that method. When your application runs at this point, the TextBox displays the name of the first product in the table. The next step is to create the navigation controls.

For the two buttons on the Windows Form, create event handlers for the Click event. Each BindingContext that is automatically created within your class for a data source contains a current position value indicating the current record it is pointing to in a specified table. Because a Windows Form can have more than one data source, the BindingContext is implemented as a collection of BindingManagerBase objects. To get the correct BindingManagerBase associated with the TextBox control, you use the BindingContext indexer passing the DataSet object and the table within the DataSet as the parameters. It returns the corresponding BindingManagerBase , which contains a property named Position . By incrementing or decrementing that property, you change the record that is currently in view and thus change the text within the TextBox control (and any other controls that are bound to that data source). Listing 14.2 shows the entirety of the application. Also, just as in the last section, as the text is edited within the TextBox , the underlying DataSet field is changed. To replicate the changes back to the database, call the Update method defined in the SqlDataAdapter class using the DataSet as a parameter.

Listing 14.2 Performing Database Updates
 using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; namespace _8_DataBoundControls {     public class Form1 : System.Windows.Forms.Form     {         private System.Windows.Forms.TextBox tbName;         private System.Windows.Forms.Button btnPrev;         private System.Windows.Forms.Button btnNext;         private System.Windows.Forms.Label label1;         private System.Data.SqlClient.SqlCommand sqlSelectCommand1;         private System.Data.SqlClient.SqlCommand sqlInsertCommand1;         private System.Data.SqlClient.SqlCommand sqlUpdateCommand1;         private System.Data.SqlClient.SqlCommand sqlDeleteCommand1;         private System.Data.SqlClient.SqlConnection sqlConnection1;         private System.Data.SqlClient.SqlDataAdapter sqlDataAdapter1;         private _8_DataBoundControls.ProductDS productDS1;         private System.ComponentModel.Container components = null;         public Form1()         {             InitializeComponent();             sqlDataAdapter1.Fill( productDS1 );         }         protected override void Dispose( bool disposing )         {             if( disposing )             {                 if (components != null)                 {                     components.Dispose();                 }             }             base.Dispose( disposing );         }         // Windows Form Designer Generated Code         [STAThread]         static void Main()         {             Application.Run(new Form1());         }         private void btnPrev_Click(object sender, System.EventArgs e)         {             tbName.BindingContext[productDS1, "Products"].Position -= 1;         }         private void btnNext_Click(object sender, System.EventArgs e)         {             this.BindingContext[productDS1, "Products"].Position += 1;         }         private void Form1_Closing(object sender,             System.ComponentModel.CancelEventArgs e)         {             if( productDS1.HasChanges() )             {                 DialogResult result;                 result = MessageBox.Show( this,                     "Would you like to save your changes?",                     "Northwind Products", MessageBoxButtons.YesNoCancel,                     MessageBoxIcon.Question );                 if( result == DialogResult.Cancel )                 {                     e.Cancel = true;                     return;                 }                 else if( result == DialogResult.No )                 {                     return;                 }                 else                 {                     sqlDataAdapter1.Update( productDS1 );                 }             }         }     } } 

Comments

A BindingContext collection is created for any object that inherits from the Control class. This collection contains each BindingManagerBase object that is used by that control and every contained control. In the code just shown, you can see that changing the Position property of a BindingManagerBase was done from the BindingContext of the form itself and not the TextBox control. You do so knowing that the change will propagate itself down the hierarchy of contained controls, of which the TextBox is one. If you create several container controls such as a GroupBox or Panel control, you can use the BindingContext for those groups to affect their contained controls, allowing you to control which controls see which current record's position of a DataSet object. While one group of controls is currently viewing one record, another group is viewing a completely different record.

When you add a DataGrid onto a Windows Form in addition to other Windows Form controls, each control has a DataSource and DisplayMember property added to its list of properties. These two properties behave similarly to the corresponding properties of the DataGrid , which means you can forego the use of the DataBinding properties. Believe it or not, even though you aren't specifically creating a data binding using the technique discussed in this section, the controls still get updated if the data source used is the same as that of the DataGrid . If you set the same data source for the DataGrid and another control, that control uses the same BindingManagerBase as the DataGrid . Therefore, when the DataGrid automatically sets the Position property as the user clicks within a new cell , the other Windows Form control is also automatically updated. You can see an example of this feature in the downloadable code available on the Sams Web site (http://www.samspublishing.com) within the 7_DataGrid project.

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

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