How to display data from database?

It is common for ListView to display data from database. In this blog, I will briefly introduce how to do this. To achieve this, we need to resolve two problems:

  1. Binding data table to ListView;
  2. Binding fields of data table to GridViewColumns.

Binding data table to ListView

How to bind data of a DataTable to ListView depend on how to use DataTable, but the basic rules are the same:

 

1. If use DataTable directly, first set the DataTable to the ListView.DataContext. And then bind ListView.ItemsSource to ListView.DataContext. The following code is a simple sample:

string connString = "CONNECTION STRING";

SqlConnection conn = new SqlConnection(connString);

SqlDataAdapter adapter = new SqlDataAdapter();

adapter.SelectCommand = new SqlCommand("COMMAND", conn);

DataSet _dataSet = new DataSet();

adapter.Fill(_dataSet, "DATATABLE NAME");

DataTable table = _dataSet.Tables["DATATABLE NAME"];

Binding bind = new Binding();

listView.DataContext = table;

listView.SetBinding(ListView.ItemsSourceProperty, bind);

 

2. If define wrapper classes for DataTable, wrapper classes should implement IEnumerable, so that instances of the wrapper classes can be directly assigned to ListView.ItemsSource. Fortunately, the Data Source Manger in Visual Studio 2005 can automatically create wrapper classes if you use it to manage your data source in your application.

3. In some cases, you may need to dynamically add data rows into the source. For example, start a background thread to insert items into the data source. In this case, you can use ObservableCollection directly or create a wrapper class implementing INotifyCollectionChanged interface .

Binding fields of data table to GridViewColumns

  1. When defining data source for ListView in the first way mentioned above, use data field names in the DisplayMemberBinding directly, for example:

<GridViewColumn DisplayMemberBinding=”{Binding FIELDNAME}”/>

 

  1. If use wrapper class for data rows, just use property names in the wrapper class.

In fact, it is straightforward to display DataTable with ListView. Two bindings are keys: one for ItemsSource of ListView and the other for fields in a row.

Declaimer: This posting is provided "AS IS" with no warranties, and confers no rights.