Up to now all of the examples that have painted the contents of a DataSet have done so by iterating through the DataTables.Rows collection for each DataTable inside the DataSet . This is non-ideal for several reasons:
The best solution to this problem is to use data binding, which connects a source of data to a consumer. The most popular source of data is the DataView because of its flexibility in filtering and sorting data automatically. The best-looking Winforms consumer of data is the DataGrid class, which is supported by the .NET Compact Framework in a limited way. Binding to a DataGridWhen a DataSet is bound to a DataGrid , the contents of the DataSet automatically appear on the DataGrid in a visually pleasing format. To bind a DataSet to a DataGrid , follow these steps:
Although a brief overview of the DataGrid is provided here, it is treated in greater detail in Chapter 3. There you can learn how to alter the look, feel, and special behavior of the DataGrid . The DataGrid is a very slimmed-down version compared to the desktop's, so there are many issues advanced programmers should be aware of when using the DataGrid on the .NET Compact Framework. The following sample code demonstrates how to bind a DataGrid with a DataView . It comes from the example application DataGrid_With_DataView: C# // Assuming that m_DataSet was already set up... m_sortAgeDataView = new DataView(m_DataSet.Tables[0]); m_sortAgeDataView.Sort = "Age DESC, Name DESC"; // Bind the DataGrid to our DataView and it will // automatically paint itself! dataGrid1.DataSource = m_sortAgeDataView; VB m_sortAgeDataView = New DataView(m_DataSet.Tables(0)) m_sortAgeDataView.Sort = "Age DESC, Name DESC" ' Bind the DataGrid to our DataView and it will ' automatically paint itself! Me.DataGrid1.DataSource = m_sortAgeDataView Using Data Binding in a Sample ApplicationThe sample application named DataGrid_With_DataView demonstrates binding a DataView to a DataGrid in a complete stand-alone application. The project files for this application are located in the folder SampleApplications\Chapter6\ . There is a C# and a Visual Basic version. DataGrid_With_DataView sets up a DataView using the same technique as was used in the DataView_Sort_And_Filter sample application. DataGrid_With_DataView uses only one DataView , which is sorted in descending order by age and name. Then, with just one line of code, the DataView binds to a DataGrid , and it displays automatically. |