basquang™ on clouds

July 24, 2009

WPF: Data Source Providers (ADO)

Filed under: WPF — basquang @ 9:34 AM

Bài viết này hướng dẫn việc binding to ADO data trong WPF.

image

Chúng ta sẽ binding Listbox cho ContactName column trong Customers table của Northwind database

Đầu tiên chúng ta thực hiện việc query data đơn giản như sau:

private DataSet GetADOData()
        {
            DataSet dtSet = new DataSet();
 
            string connectionString = @"Data Source=(local)\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True";
            string sql = "SELECT ContactName, Address FROM Customers";        
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand command = new SqlCommand(sql, connection);
                SqlDataAdapter adapter = new SqlDataAdapter();
                connection.Open();
                adapter.SelectCommand = command;
                adapter.Fill(dtSet, "Customers");                
            }
            return dtSet;
        }

Sau đó chúng thực hiện việc gán DataContext cho listbox:

...
InitializeComponent();
lbCustomers.DataContext = GetADOData();   
...
 
XAML code chúng ta khai báo
<ListBox Name="lbCustomers" 
                 ItemsSource="{Binding Tables[0]}" 
                 DisplayMemberPath="ContactName">
</ListBox>

Các bạn sẽ được kết quả hiển thị Binding từ ADO như trên.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: