DataViews and Data Binding—Displaying Multiple Views


Jump to: navigation, search
CSharp-Online.NET:Articles
Database Articles

DataViews and Data Binding

© 2003 O'Reilly Media, Inc.

Displaying Multiple Views

One of the most useful aspects of the DataView is the ability to create multiple DataView objects to provide different representations of the same data. This technique is quite straightforward and is shown in Example 12-3 with three separate DataGrid controls. Each DataView applies a different SQL filter expression using the RowFilter property.

Example 12-3. Binding the same data with different views

private void MultipleView_Load
  (object sender, System.EventArgs e)
{
  string connectionString = "Data Source=localhost;" +
    "Initial Catalog=Northwind;Integrated Security=SSPI";
  string SQL = "SELECT * FROM Customers";
 
  // Create ADO.NET objects.
  SqlConnection con = new SqlConnection(connectionString);
  SqlCommand com = new SqlCommand(SQL, con);
  SqlDataAdapter adapter = new SqlDataAdapter(com);
  DataSet ds = new DataSet("Northwind");
 
  // Execute the command.
  try
  {
    con.Open();
    adapter.Fill(ds, "Customers");
  }
  catch (Exception err)
  {
    Console.WriteLine(err.ToString());
  }
  finally
  {
    con.Close();
  }
  // Create views.
  DataView viewArgentina = new DataView(ds.Tables["Customers"]);
  DataView viewBrazil = new DataView(ds.Tables["Customers"]);
 
  // Filter views.
  viewArgentina.RowFilter = "Country = 'Argentina'";
  viewBrazil.RowFilter = "Country = 'Brazil'";
 
  // Perform data binding.
  gridArgentina.DataSource = viewArgentina;
  gridBrazil.DataSource = viewBrazil;
  gridAll.DataSource = ds.Tables["Customers"].DefaultView;
}

Notice that if you modify a row in one view, the changes appear automatically in all other views. Remember, there is only one data source—the linked DataTable.

Figure 12-4 shows the three views, each of which contains only a subset of the full data in the DataTable.


Image:ADONETNutshell12-4x.jpg
Figure 12-4. Multiple views of the same data


Previous_Page_.gif Next_Page_.gif


Personal tools