Data Binding Samples


The next section will show you some samples of data binding. Some of these samples will be review (such as the simple binding and ComboBox binding), but the DataGrid sample will be entirely new. Before going on to discuss more advanced data binding topics, you should see the DataGrid binding in action and understand how it works in conjunction with the currency manager and the BindingContext.

Simple Binding

As you saw earlier, simple binding involves the association of a single value on a data source with a single property value on a control. This is accomplished by adding a new binding instance to the DataBindings collection, as shown here:

 lblDescription.DataBindings.Add("Text", objDataSource, "Description"); 

All the code that you saw earlier dealing with the PropertyManager (obtained through the BindingContext class) applies to simple binding concepts. One of the most common uses for simple binding is to automatically store and retrieve control properties such as size, location, colors, and so forth in an effort to remember user preferences.

Binding to a ComboBox

Earlier in the chapter, you saw an example of binding to a ListBox control. Binding to a ComboBox control is no different. All you do is set the DataSource property of the control, as well as the DisplayMember and ValueMember properties, if applicable. After that has been done, you can use the control properties and the members of the CurrencyManager class to create a rich, data-bound user experience.

DataGrid Binding

This brings up the topic of binding to a DataGrid. The DataGrid is at once one of the most powerful WinForms controls and the most frustrating. It can save you a lot of time if it is used properly, but it can cause you an endless amount of frustration if it isn't used properly.

The DataGrid sample you are going to see doesn't allow inline editing within the grid. Although it is useful to know how this works, there are very few actual user interfaces where this is actually a desired behavior. More often than not, the DataGrid is used to display columnar data and to allow the user to browse. After the user has found the record he wants to work with, he double-clicks it to open an additional editor that might also display data related to that record. You'll see how to use a CurrencyManager to take care of that.

Listing 30.3 shows a sample form that has on it a single DataGrid, two buttons, and a context menu associated with the grid. The first button simply retrieves data from the Northwind sample database in SQL 2000 (you can change your code to get it from the Access database if you don't have a copy of SQL installed). The second button and the context menu simulate what the code might look like if you were to launch a user editor dialog based on the current position of the cursor within the DataGrid. The most refreshing thing to notice is that this code doesn't do any hit testing, nor does it look at any two-dimensional array of cells; all it does is look at the BindingContext, which is always the simplest way to get at the current row of any data source.

Listing 30.3. An Illustration of DataGrid Binding and Interaction with a CurrencyManager
 using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Data.SqlClient; namespace DataGridBinding { public class Form1 : System.Windows.Forms.Form {   private System.Windows.Forms.DataGrid dataGrid1;   private System.Windows.Forms.Button button1;   private System.Windows.Forms.Button btnEdit;   private System.Windows.Forms.ContextMenu cmGrid;   private System.Windows.Forms.MenuItem cmiEditUser;   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 );   }   // Windows Forms designer code cut out for clarity   [STAThread]   static void Main()   {     Application.Run(new Form1());   }   private void button1_Click(object sender, System.EventArgs e)   {      SqlConnection conn =        new SqlConnection(        "server=localhost; User ID=sa; Password=password; Initial Catalog=Northwind;");      conn.Open();      SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Customers", conn);      DataSet dsCustomers = new DataSet();      da.Fill(dsCustomers,"Customers");      dataGrid1.DataSource = dsCustomers.Tables["Customers"];   }   private void btnEdit_Click(object sender, System.EventArgs e)   {     CurrencyManager cm = (CurrencyManager)BindingContext[ dataGrid1.DataSource ];     DataRowView drv = (DataRowView)cm.Current;     System.Diagnostics.Debug.WriteLine(       "About to edit customer " + drv["CustomerID"].ToString());     // launch user editor with drv as parameter   }   private void cmiEditUser_Click(object sender, System.EventArgs e)   {     CurrencyManager cm = (CurrencyManager)BindingContext[ dataGrid1.DataSource ];     DataRowView drv = (DataRowView)cm.Current;     System.Diagnostics.Debug.WriteLine(       "About to edit customer " + drv["CustomerID"].ToString());     // launch user editor with drv as parameter   }   } } 

When you play around with this sample, you'll begin to see how powerful it really is. Although it might not be flashy or complicated, it does illustrate a very powerful principle. When using a DataGrid that can be extremely complicated visually, especially when displaying entire hierarchies of data, all you need to remember is that you can always rely on the BindingContext and the CurrencyManager. These classes will always be there, and they will always give you the right information quickly and easily. When many developers are first learning Windows Forms, they often learn nothing of the BindingContext class or of the CurrencyManager class. As a result, many think that Windows Forms data binding is complex and difficult. After developers obtain a firm grasp on the big picture of how everything works and how all the data binding facets are interrelated, Windows Forms data binding is actually very pleasant, quick, and powerful.

After you have played with a technology to the point where the information no longer intimidates you, you can begin to create some incredible solutions, especially with powerful tools such as Windows Forms data binding. Tinker with the samples you have seen in this chapter until you feel that you have mastered the samples. The following advanced binding samples will be much easier to follow at that point.



    Visual C#. NET 2003 Unleashed
    Visual C#. NET 2003 Unleashed
    ISBN: 672326760
    EAN: N/A
    Year: 2003
    Pages: 316

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