Chương 8 TÌM HIỄU VÀ ỨNG DỤNG CƠ CHÉ DATA BINDING Các vấn đề chính sẽ được đề cập: v Giới thiệu Data Binding v Các dạng Data Binding Kết thúc chương này các bạn có thẻ: > Sử dụng kỹ thuật DataBinding với các đối tượng dữ liệu (data controls) trong tng dung ASP. GIOI THIEU DATABINDING ASP.NET cung cấp cho chúng ta rất nhiều điều khiển để cho phép hiển thị cũng như tiếp nhận thông tin từ người dùng. Có những điều khiển cho phép chúng ta hiển thị những thông tin tinh (Static — tức là giá trị xác định được ngay khi lập trình), một số hiển thị được cả những thông tin động (Dynamic - tức là được tính toán khi chạy chương trình). Đề việc hiển thị thông tin động này một cách đơn giản và nhanh chóng, ASP.NET cung cấp cho chúng ta một đặc tính gọi là "Data Binding" (kết nối dữ liệu).
Data Binding là một kỹ thuật kết nói dữ liệu với những đối tượng. Sử dụng data binding, bạn có thể nối dữ liệu trong một nguôn dữ liệu đến một đối tượng người dùng. Mọi việc thay đổi trên các đối tượng giao diện người dùng có thể trực tiếp được cập nhật vào nguồn dữ liệu. Tir "data" cũng cần phải được hiểu theo nghĩa rộng, nó không nhất thiết phải là cái gì đó liên quan đến Cơ sở đữ liệu như ta thường nghĩ mà có thể là một thuộc tính, một mảng, một tập hợp, một danh sách, một trường dữ liệu trong bảng CSDL.
hay tổng quát là một biểu thức trả về giá trị. Có hai kiéu binding di liệu đó là Simple Data Binding và Repeated Data Binding. Ching ta quan tâm nhiều đến kiểu thứ hai— Repeated Data Binding- với nguồn đữ liệu được truy xuất từ cơ sở dữ liệu. CAC DANG DATA BINDING 8.
Dạng kết nối dữ liệu đơn (Single Data Binding) Trong ASP.NET, có thể gắn một giá trị đơn lẻ vào trang được gọi là Single Data Binding. Cú pháp đê găn dữ liệu đơn vào trang như sau: <%# biêu_thức %> Trong đó: biểu thức có thể là một hằng, một biến, một hàm, một biểu thức hoặc có thê là một thuộc tính khác. Một số cách dung dang kết nối dữ liệu đơn: Hằng SỐ:<%# 20 %> <br /> Hằng xâu: <%# "Xin chào" %> <br /> Biểu thức: <9# 10+5 %> <br/> Hàm: <%# "Sin(3. 14/2) %> <br /> Thuộc tính khác: <%# "Tiêu đề của trang là " + this.Title %> Có thể gắn kết tới một biểu thức, một biến, thuộc tính.
Chú ý: Trong thủ tục Page_Load cần thêm lệnh this.DataBindQ để thực sự gắn kết. Thí dụ 1: Tạo trang SimpleDataBinding.aspx minh hoa dang kết nối dữ liệu đơn giản. Phần mã lệnh thiết kế trang SimpleDataBinding.aspx trong đó có sử dụng dạng kết nỗi dữ liệu đơn giản với biến TransactionCount. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="SimpleDataBinding.cs" Inherits="SimpleDataBinding" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.org/TR/xhtml1 1/DTD/xhtml] | .dtd"> <html xmIns="http://www.org/1999/xhtml" > <head runat="server"> <title>Simple Data Binding</title> <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> 370 <div> <asp:Label id="IbIDynamic" runat="server" Font-Size="X-Large" > There were <%# TransactionCount %> transactions today.
I see that you are using <%# Request. </asp:Label> </div> </form> </body> </html> Phan mã lệnh thực thi trang SimpleDataBinding.cs: public partial class SimpleDataBinding: System.Page { protected int TransactionCount; protected void Page_Load(object sender, EventArgs e) { // (You could use database code here // to look up a value for TransactionCount.) TransactionCount = 10; // Now convert all the data binding expressions on the page.DataBind(); } Kết quả thực thi trang SimpleDataBinding.aspx: There were 10 transactions today. I see that you are using Firefox. Dạng kết nối dữ liệu có sự lặp lại (Repeated Data Binding) Có rất nhiều trường hợp dữ liệu cần hiển thị là một danh sách (như: mảng, bảng, DataReader,.) hay tông quát là một tập hợp các mục (Collection Items).
Trong trường hợp như vậy, hoàn toàn có thể dùng cơ chế DataBinding trong ASP.NET để gắn kết quả đó vào một điều khiển dạng danh sách (như ListBox, DropdownList, CheckboxList,.) để hiên thị mà không cần phải viết nhiều dòng code. 371 Các điều khiển cho phép gắn kết đữ liệu thường có ba thuộc tính với các ý nghĩa như sau: DataSource: 1a thudc tinh để chỉ đến nguồn dữ liệu cần gắn kết. Nguôn dữ liệu này phải là một tập hợp. Ví dụ: DataTabe, Array,.
DataSourcelD: chỉ đến một đối tượng cung cấp nguồn dữ liệu. Có thê sử dụng hoặc thuộc tính DataSourcelD hoặc DataSource nhưng không được cả hai. DataTextField: cho biết là gắn kết với trường nào của mỗi mục đữ liệu. Thí dụ 2 Tạo trang ListDataBinding.aspx mỉinh họa kết nối dữ liệu dạng Repeated Data Binding Phần mã lệnh thiết kế trang ListDataBinding.aspx: <%(@ Page Language="C#" AutoEventWireup="true" CodeFile="ListDataBinding.cs" Inherits="ListDataBinding" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.org/TR/xhtml11/DTD/xhtml] 1 .dtd"> <html xmins="http://www.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> <link href="StyleSheet.css” rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <div> <asp:ListBox id="MyListBox" runat="server" Width="197px" Height="193px"></asp:ListBox> <br /><br /> <select id="MyHTMLSelect" size="1" runat="server"/> <br /><br /> <asp:DropDownList id="MyDropDownListBox" runat="server" Width="248px" Height="22px"></asp:DropDownList> <br /><br /> 372 <asp:CheckBoxList id="MyCheckBoxList" runat="server" Width="201 px" Height="157px"></asp:CheckBoxList> <br /><br /> <asp:RadioButtonList id="MyRadioButtonList" runat="server" Width="249px" Height="158px"></asp:RadioButtonList> </div> </form> </body> </html> Phần mã lệnh thực thi trang ListDataBinding.cs: public partial class ListDataBinding: System.Page { protected void Page_Load(object sender, EventArgs e) { // Create and fill the collection.
List<string> fruit = new List<string>(); fruit.Add("Plum"); // Define the binding for the list controls.DataSource = fruit; MyDropDownListBox.DataSource = fruit; MyHTMLSelect.DataSource = fruit; MyCheckBoxList.DataSource = fruit; MyRadioButtonList.DataSource = fruit; // Activate the binding.DataBind(); } } Kết quả thực thí cho thay rõ sự kết nói dữ liệu từ tập dữ liệu List<string> đến các điêu khiên đữ liệu của ASP.NET: 373 Kini R Peat Mango Blueberry lượn Peach Plum [flmanao Blueberry Apricot [flsanana © mango © Blueberry © apricot © Banana ©peach Ô plum _ Chú ý: Nếu không có phát biểu this.DataBindQ thì sẽ không có kêt quả như trên. Thí dụ 3: Tạo trang DataSetBindingaspx liên kết dữ liệu ListBox với đối tượng ADO.NET là DataSet Phần mã lệnh thiết kế trang DataSetBinding.aspx: 374 <%( Page Language="C#" AutoEventWireup="true" CodeFile="DataSetBinding.cs" Inherits="DataSetBinding" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.org/TR/xhtml1 1/DTD/xhtml] | .dtd"> <html xmlns="http://www.org/1999/xhtml|" > <head runat="server"> <title>Untitled Page</title> <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form|" runat="server"> <div> <asp:ListBox ID="IstUser" runat="server" Height="152px" Width="192px"></asp:ListBox></div> </form> </body> </html> Phần mã lệnh thực thi trang DataSetBinding.cs: public partial class DataSetBinding: System.Page { protected void Page_Load(object sender, EventArgs e) { // Define a DataSet with a single DataTable. DataSet dsInternal = new DataSet(); dsInternal.Add("Users"); // Define two columns for this table.Add("Country"); // Add some actual information into the table. DataRow rowNew = dsInternal.NewRow(): rowNew|"Name"| = "John"; 375 rowNew["Country"] = "Uganda"; dsInternal.Add(rowNew); rowNew = dsInternal.NewRow(;, rowNew["Name"|] = "Samantha"; rowNew["Country"] = "Belgium"; dsInternal.Add(rowNew); rowNew = đsInternal.NewRowQ; rowNew["Name"| = "Rico"; rowNew["Country"] = "Japan"; dsInternal.Add(rowNew); // Define the binding.DataTextField = "Name"; // Define the binding.DataSource = dsInternal; IstUser.DataMember = "Users"; IstUser.DataTextField = "Name"; this.DataBind(); // Could also use IstItems.DataBind() to bind just the list box.
} Kết quả thực thi: John a Rico 376 BÀI TẬP CHƯƠNG 8 Bài 1: Thực hiện các bài tập thí dụ trong bài học để nắm vững nội dung của bài. Bài 2: Tạo trang ASP.NET kết nối đữ liệu với đối tượng ảnh Image: <asp:Image id="imgDynamic" ImageUrl="<9%# URL %>" runat="server" /> Đối tượng Label: <asp:Label id="IbIDynamic" runat="server"><%i# URL %></asp:Label> Đối tượng CheckBox: <asp:CheckBox id="chkDynamic" Text="<%# URL %>" runat="server" /> Đối tượng HyperLink: <asp:Hyperlink id="InkDynamic" Text="Click here!" NavigateUrl="<%# URL %>" runat="server" /> Phần mã lệnh thiết kế trang DataBindingUrl.aspx: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataBindingUrl.cs" Inherits="DataBindingUrl" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.org/TR/xhtml1 1/DTD/xhtml] |.dtd"> <html xmins="http://www.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="IbIDynamic" runat="server"><%# URL %></asp:Label> <br /><br /> <asp:CheckBox id="chkDynamic" Text="<%# URL %>" runat="server" /> <br /><br /> 377 <asp:Hyperlink id="InkDynamic" Text="Click here!" NavigateUrl="<%# URL %>" runat="server" /> <br /><br > <asp:Image id="imgDynamic" ImageUrl="<%# URL %>" runat="server" /> </div> </form> </body> </html> Phần mã lệnh thực thi trang: public partial class DataBindingUrl: System.ULPage { public string URL; protected void Page_Load(Object sender, EventArgs ¢) { URL = "Images/picture.DataBind(); } Kết quả thực thi: Irnages/picture.Jpg \Y Images/picture.jpg Click here! Bài 3: Tạo trang ASP.aspx gắn kết dữ liệu của bảng Product trong CSDL Northwind với các điều khiên dữ liệu Label và ListBox trén trang. 378 Phần mã lệnh thiết kế trang RecordEditor.aspx: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="RecordEditor.cs" Inherits="RecordEditor" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.org/TR/xhtml 1 1/DTD/xhtml] | .dtd"> <html xmins="http://www.org/1999/xhtml" > <head runat="server"> <title>Record Editor</title> <link href="StyleSheet.css” rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <div> <asp:DropDownList [D="IstProduct" runat="server" AutoPostBack="True" Width="280px" OnSelectedIndexChanged="IstProduct_SelectedIndexChanged"> </asp:DropDownList> <br > <br > <hr > <br > <table> <tr> <td style="width: 234px" valign="top"> <asp:Label ID="Ib]RecordInfo" runat="server"></asp:Label></td> <td style="width: 190px"> <asp:Panel ID="pnlCategory" runat="server" Visible="False"> <asp:ListBox ID="IstCategory" runat="server" Height="120px" Width="152px"> </asp:ListBox><br /> <br /> <asp:Button ID="cmdUpdate" runat="server" Text="Update" OnClick="cmdUpdate_Click" /> </asp:Panel> </td> </tr> </table> 379 </div> </form> </body> </html> Phần mã lệnh thyc thi trang RecordEditor.cs: public partial class RecordEditor: System.ULPage { private string connectionString = WebConfigurationManager.ConnectionString; protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { // Deñne the ADO.NET objeets for selecting Produets. string selectSQL = "SELECT ProductName, ProductID FROM Products"; SqlConnection con = new SqlConnection(eonnectionString); SqlCommand emd = new SqlCommand(selectSQL, con); // Open the connection.Open(); // Define the binding.DataTextField = "ProductName"; IstProduct.DataValueField = "ProductID"; // Activate the binding.Close(); // Make sure nothing is currently selected.SelectedIndex = -1; } } protected void IstProduct_SelectedIndexChanged(object sender, EventArgs e) 380 // Create a command for selecting the matching product record.
string selectProduct = "SELECT ProductName, QuantityPerUnit, " + "CategoryName FROM Products INNER JOIN Categories ON " + "Categories.CategoryID " + "WHERE ProductID=@ProductID"; // Create the Connection and Command objects. SqlConnection con = new SqlConnection(connectionString); SqlCommand emdProducts = new SqiCommand(selectProduct, con); emdProducts.Add With Value("@ProductID", IstProduct. Value); // Retrieve the information for the selected product.Open(); SqlDataReader reader = emdProducts.ReadQ; // Update the display.Text = "<b>Product:</b> " + reader["ProductName"] + "<br i"; IblReeordInfo.Text += "<b>Quantity:</b> " + reader|"QuantityPerUnit"] + "<br >" IbIRecordInfo.Text += "<b>Category:</b> " + reader["CategoryName"]; // Store the corresponding CategoryName for future reference. string matchCategory = reader["CategoryName"].ToString(); // Close the reader.Close(); // Create a new Command for selecting categories.
string selectCategory ELECT CategoryName, Category[D FROM Categories"; SqlCommand emdCategories = new SqlCommand(selectCategory, con); / Retrieve the category information, and bind it.DataTextField = "CategoryName"; IstCategory.DataValucField = CategoryID"; IstCategory.DataBind(); 381 // Highlight the matching category in the list.Selected = true; } pniCategory. Visible = true; } protected void emdUpdate_Click(object sender, EventArgs e) { // Define the Command. string updateCommand = "UPDATE Products " + "SET CategoryID=@CategoryID WHERE ProductID=@ProductID"; SqlConnection con = new SqlConnection(connectionString); SqlCommand emd = new SqlCommand(updateCommand, con); cmd.AddWithValue("@CategoryID", IstCategory.AddWithValue("@ProductID", IstProduct. Value); // Perform the update.ExecuteNonQuery(); } Kết quả thực thi: Đầu tiên hiền thị nội dung một DropdownList: Aniseed Syrup x Khi chọn giá trị trong DropdownList trên sẽ gây ra sự kiện IstProduct_SelectedIndexChanged(object sender, EventArgs e) va sẽ hiên thị kêt quả lựa chọn: 382 Aniseed Syrup Product: Aniseed Syrup aaa a Quantity: 12 - 550 ml bottles Category: Condiments Confections Dairy Products Grains/Cereals Meat/Poultry Produce x LUpdate_} Dé ý thấy giá trị trong ListBox đang chọn chứa thông tin Category của mẫu tin Produet vừa được chọn.
Nếu thay đổi giá trị khá ic va click nút Update đữ liệu mới thay đổi của vùng Category trên mẫu tin hiện tại sẽ được cập nhật lại và hiện ra ở lần chọn sau. Aniseed Syrup Product: Aniseed Syru ; 5 Condiments ondiments Confections Dairy Products Grains/Cereals Meat/Poultry Produce x Kết quả hiện ra ngay sau khi chọn lại sản phẩm này.