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 CustomerID 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(customerIdTextBox.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 customerId) { String companyName = "Not found."; if (customerIdTextBox.Text != "") { // Create a command to retrieve the company name for the // user-specified customer ID. String ...

Get ADO.NET Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.