O'Reilly logo

ADO.NET Cookbook by Bill Hamilton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required