Binding to Other Simple Controls

The simplest binding is to bind one control (for example, a label) to another control (e.g., a list box). As a demonstration of data-binding one control to a second, add a new label to the form, and bind its contents to the drop-down selection:

<tr>
   <td>
      Chosen Book Title
   </td>
   <td>
      <asp:Label 
      Text="<%# ddlBooks.SelectedItem.Text %>" 
      Runat="server" />
   </td>
</tr>

This new label control is bound to the text value of the selected item in ddlBooks. The <%# %> tags accomplish the data binding. The only additional change to the code is in WebForm1_Load, where you bind the entire page, rather than a single control:

Page.DataBind(  )

You could, of course, bind each of the controls individually rather than binding the entire page. In any case, the result, shown in Figure 9-3 is that the control is bound to the text of the control.

Data binding to a control

Figure 9-3. Data binding to a control

Get Programming ASP.NET, Second Edition 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.