2010/08/30

WPF: Binding a ListView to DataTable

Suppose you have a DataTable filled with data. And want a ListView to present the data. This code sample can help you.

XAML

<ListView Name="lv">
    <ListView.View>
        <GridView>
        </GridView>
    </ListView.View>
</ListView>

C#

string tableName = “some_table_name”;
DataSet ds = Dao.GetData(tableName);  // A class to retrieve dataset.
if (ds.Tables == null || ds.Tables.Count == 0)
    return;

GridView gv = (GridView)lv.View;

DataTable dt = ds.Tables[0];
foreach (DataColumn col in dt.Columns) {
    GridViewColumn gvCol = new GridViewColumn();
    gvCol.Header = col.ColumnName;
    gvCol.DisplayMemberBinding = new Binding(col.ColumnName);
    gvCol.Width = 100;
    gv.Columns.Add(gvCol);
}

lv.ItemsSource = ((IListSource)dt).GetList();

1 comment:

thankyou said...

Great post. this is what i had been searching for.... thanks a lot. all other f**** were just copying from each other.