Thứ Sáu, 24 tháng 7, 2009

WPF: Data Source Providers (ADO)

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

A21319952F68E79E_429_0[1]

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

Không có nhận xét nào:

Đăng nhận xét