Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Binding Simple Data to Web Forms Controls Problem You need to bind a field of data to a server-side control. Solution Use the DataBind( ) method. The Web Forms page sample code displays | Team LiB Recipe 7.1 Binding Simple Data to Web Forms Controls Problem You need to bind a field of data to a server-side control. Solution Use the DataBind method. The Web Forms page sample code displays the company name for the CustomerlD specified by assigning the method GetCompanyName which is defined in the code-behind file to the Text property of TextBox control companyNameTextBox. The code for the Web Forms page is shown in Example 7-1. Example 7-1. File ADOCookbookCS0701.aspx asp TextBox id companyNameTextBox style Z-INDEX 103 LEFT 136px POSITION absolute TOP 128px runat server ReadOnly True Width 280px Text GetCompanyName customerldTextBox.Text asp TextBox The code-behind contains one event and one method Page.Load Binds data from the source in this case the GetCompanyName method to the companyNameTextBox server control. GetCompanyName This method retrieves and returns the company name for a specified customer ID. The C code for the code-behind is shown in Example 7-2. Example 7-2. File ADOCookbookCS0701.aspx.cs Namespaces variables and constants using System using System.Configuration using System.Data using System.Data.SqlClient . . . private void Page_Load object sender System.EventArgs e companyNameTextBox.DataBind public String GetCompanyName String customerld String companyName Not found. if customerldTextBox.Text Create a command to retrieve the company name for the user-specified customer ID. String sqlText SELECT CompanyName FROM Customers WHERE CustomerID customerldTextBox.Text . SqlConnection conn new SqlConnection ConfigurationSettings.AppSettings DataConnectString SqlCommand cmd new SqlCommand sqlText conn conn.Open Execute the command. companyName cmd.ExecuteScalar .ToString conn.Close return companyName Discussion Simple data binding binds an ASP.NET web control property to a single value in a data source. The values can be determined at runtime. Although most commonly used to set control properties to display data any property of the control