Data for Silverlight
Bind the Data to Controls on the Page
The Sample Application > Implement the Client Side > Bind the Data to Controls on the Page

After the data is retrieved, we bind it to the controls on the page. Here is the implementation of the BindData method that handles that task:

C#
Copy Code
void BindData()
{
  // Get the tables we want
  DataTable dtCategories = _ds.Tables["Categories"];
  DataTable dtProducts = _ds.Tables["Products"];

  // Populate categories grid
  _gridCategories.ItemsSource =
      new DataView(dtCategories,
          "CategoryID", "CategoryName", "Description");

  // Populate products categories grid
  _gridProducts.ItemsSource = dtProducts.DefaultView;
}

 

Note: If you have ever written WinForms or ASP.NET applications, this code looks familiar. This is one of the strengths of C1.Silverlight.Data. It allows you to leverage your knowledge of ADO.NET in Silverlight applications. You can use the DataSet object model to inspect and modify the tables available for data binding, including their schemas and data, as well as the data relations, keys, and so on.

 

The only slightly unusual statement is the one that creates a DataView object and specifies which columns to include in the view. This is an extension provided by the C1.Silverlight.Data implementation that is not present in the original ADO.NET DataView class.

If you run the project now, you see the data retrieved from the server:

Data retrieved from server displayed in the grid.

Before we continue with the sample, a few comments are in order.

Although the code that binds the data to the controls looks familiar, what happens under the covers is quite different from the traditional WinForms and ASP.NET scenarios. All data binding in WPF and Silverlight is done through reflection. But the DataRowView objects exposed by DataView collections do not have properties that match the columns in the underlying DataTable ("CategoryID", "CategoryName", "Description", and so on).

Note: The binding is possible because the DataView class dynamically creates anonymous types that derive from DataRowView and expose additional properties that correspond to the table columns. Controls can then use reflection to find these properties and bind to them.

The DataRow class also leverages this mechanism through its GetRowView method. This method builds a wrapper object that exposes selected properties of the DataRow and can be used for data binding. You can use this method in your LINQ queries.

For example, the code below builds a LINQ query that selects all categories that start with "C" and exposes their name and description:

C#
Copy Code
_gridCategories.ItemsSource =
    from dr
    in dtCategories.Rows
    where ((string)dr["CategoryName"]).StartsWith("C")
    select dr.GetRowView("CategoryName", "Description");

If you call GetRowView with no parameters, all columns are exposed.

See Also