Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I bind data from an MDB file to a control?

Use the classes in the System.Data.OleDb namespace to read an MDB file into a DataSet, then bind the DataSet to one or more controls like ListBox and a ComboBox. First you instantiate a OleDbConnection object using a connection string to your MDB file. Next you then instantiate a OleDbDataAdapter that uses this connection object and a SQL query. Next you create a DataSet object, use the OleDbDataAdapter to fill this dataset. Finally you bind this dataset to your control. Here is the code that does this.

using System;
using System.Data;
using System.Data.OleDb;
using System.ComponentModel;
using System.Windows.Forms;

public class Form1 : Form
{
  private ListBox listBox1;
  private ComboBox comboBox1;

  // ...

  private void Form1_Load( object sender, EventArgs e )
  {
    LoadCustomers( @"C:\northwind.mdb" );
  }

  private void LoadCustomers( string filename )
  {
    string connectionString =
      string.Format( "Provider=Microsoft.JET.OLEDB.4.0;data source={0}",
          filename );
    string selectCommandText = "SELECT * FROM Customers";

    // fill dataset from MDB file
    OleDbConnection connection =
      new OleDbConnection( connectionString );
    OleDbDataAdapter dataAdapter =
      new OleDbDataAdapter( selectCommandText, connection );
    DataSet dataSet = new DataSet();
    dataAdapter.Fill( dataSet, "Customers" );

    // attach dataset's DefaultView to the listBox1
    listBox1.DataSource = dataSet.Tables[ "Customers" ].DefaultView;
    listBox1.DisplayMember = "CustomerID";

    // attach dataset's DefaultView to comboBox1
    comboBox1.DataSource = dataSet.Tables[ "Customers" ].DefaultView;
    comboBox1.DisplayMember = "CustomerID";
  }

}

Notice that this code uses the same DataSet object for both the ListBox and the ComboBox. When done in this manner, the two controls are linked: a selection in one control will be the selection in the other control. If you edit an entry in the ComboBox, the same entry is the ListBox is changed. To avoid this linkage, simply create a second DataSet object for your second control.

Contributed from George Shepherd's Windows Forms FAQ



Page view counter