WPF + ADO?

If you have a WinForms background, you are sure to have used ADO.NET! One of the question I get asked is how do I bind to ADO.NET, LINQ, etc... Here is a very basic example of how to bind to ADO.NET objects.

Note: I am using the standard AdventureWorks database available from CodePlex.

My Window XAML only has a ListBox

<ListView x:Name="listBox" />

Here is my connection string and my SQL query

const string connectionString = @"Data Source=rudi-lt\sqlexpress;Initial Catalog=AdventureWorks;Integrated Security=True";
const string sqlQuery = "SELECT * FROM Person.Contact";

Next, lets retrieve the DataTable

SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(sqlQuery,connection);
command.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet, "Person.Contact");
listBox.ItemsSource = dataSet.Tables[0].DefaultView;

The only important thing to note here is that you can't bind directly to the DataTable! Instead, you have to use the DataView. Every DataTable has a ready-made DataView object available through the DataTable.DefaultView property.

And that is it!

Note: The DataView class implements the IBindingList interface, which implements change notification. This is similar to INotifyCollectionChanged!

Published Monday, May 05, 2008 9:28 AM by rudi
Filed under: , ,

Comments

# WPF ADO?

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Monday, May 05, 2008 9:42 AM by DotNetKicks.com