In Depth ASP.NET using ADO.NET

Data Binding Expressions

Now we will use another approach to this issue of data binding; Data Binding Expression. Data binding expressions create bindings between any property on an ASP.NET page, including server control properties, and a data source when the DataBind method is called on the page. We can include data binding expressions on the value side of an attribute/value pair in the opening tag of a server control or anywhere in the page.

<tagprefix:tagname property="<%# databinding expression %> runat="server" />

Or

literal text <%# databinding expression %>

Regardless of where we place them, all data binding expressions, must be contained in <%# and %> characters. ASP.NET supports a hierarchical data binding model that supports associative bindings between server control properties and parent data sources. Any server control property can be data bound against any public field or property on the containing page or on the server control's immediate naming container.

The ASP.NET supplies a static method, called DataBinder.Eval that evaluates late-bound data binding expressions and optionally formats the result as a string. This method eliminates much of the explicit casting we must do to coerce values to the data type we desire. For example; in the following code piece, an integer is displayed as a currency string. We must first cast the type of the data row in order to retrieve the data field, IntegerValue, with the standard ASP.NET data binding syntax. Next, this is passed as an argument to the String.Format method:

<%# String.Format("{0:c}", ((DataRowView)Container.DataItem)["IntegerValue"]) %>

Contrast this syntax with that of DataBinder.Eval, which has only three arguments: the naming container for the data item, the data field name, and a format string. In a templated list like DataList Class, DataGrid Class, or Repeater Class, the naming container is always Container.DataItem.

<%# DataBinder.Eval(Container.DataItem, "IntegerValue", "{0:c}") %>

The format string argument is optional. DataBinder.Eval returns a value of type object, if it is omitted, as in the following example:

<%# (bool)DataBinder.Eval(Container.DataItem, "BoolValue") %>

When data binding controls within a templated list DataBinder.Eval is particularly useful, since often both the data row and the data field must be cast. The following source code demonstrates how we can data bind against properties in an ASP.NET server control. The Label Web server control data binds against the selected item in the list when a user selects a state from the DropDownList Web server control.

<html>
<head>
<script language="C#" runat="server">
void SubmitBtn_Click(Object sender, EventArgs e) {
// Rather than explictly pull out the variable from the "StateList"
// and then manipulate a label control, just call "Page.DataBind".
// This will evaluate any <%# %> expressions within the page. 
         
        Page.DataBind();
}
    </script>
</head>
<body>
<h3><font face="Verdana">Data binding to a property of another server control</font></h3>
    <form runat="server">
        <asp:DropDownList id="StateList" runat="server">
          <asp:ListItem>CA</asp:ListItem>
          <asp:ListItem>IN</asp:ListItem>
          <asp:ListItem>KS</asp:ListItem>
          <asp:ListItem>MD</asp:ListItem>
          <asp:ListItem>MI</asp:ListItem>
          <asp:ListItem>OR</asp:ListItem>
          <asp:ListItem>TN</asp:ListItem>
<asp:ListItem>UT</asp:ListItem>
</asp:DropDownList>     
<asp:button Text="Submit" OnClick="SubmitBtn_Click" runat="server"/>       
        <p>   
Selected State: <asp:label text='<%# StateList.SelectedItem.Text %>' runat="server"/>   

    </form>
</body>
</html>

Binding a RadioButtonList to a DataSource

The RadioButtonList control's programmatic functionality is almost identical to the CheckBoxList, but in fact it is different. When rendered, each item from the RadioButtonList.DataSource will be part of a group of RadioButton controls and we can only select one RadioButton out of the group at one time. The RadioButtonList is part of the List controls suite, therefore its behavior is the same as the proceeding List controls as far as how we enable automatic post back (AutoPostBack), how we tell if an item is checked (ListItem.Selected), and how to handle the SelectedIndexChanged on the post back. Therefore, we will be continuing with the code example now. This source code piece demonstrates how to use all the proceeding attributes and events to determine item selection.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script runat="server" language="C#" >
void Page_Load(Object sender, EventArgs e) {
  if (! IsPostBack) {
  rbl_DataBind();
  }
}
void rbl_DataBind(){
  SqlConnection SqlCon = new SqlConnection("server=localhost;uid=sa;pwd=;database=northwind");
  SqlCommand SqlCmd = new SqlCommand("SELECT TOP 21 ProductName, ProductID FROM Products", SqlCon);
  SqlCon.Open();
  rbl.DataSource = SqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
  rbl.DataTextField = "ProductName";
  rbl.DataValueField = "ProductID";
  rbl.DataBind();
}
void RadioButtonList_SelectedIndexChanged(Object sender, EventArgs e) {
  StringBuilder sb = new StringBuilder("<b><u>Item Selected</u></b><p>");
  int i;
  for(i = 0; i < rbl.Items.Count; i++){
  if(rbl.Items[i].Selected) {
    sb.Append(i);
    sb.Append(" - ");
    sb.Append(rbl.Items[i].Text);
    sb.Append("<br>");
  }
  }
  lCheckBoxList.Text = sb.ToString();
}
</script>
<html>
<body>
  <form runat="server">
    <asp:Label
    width="100%"
    runat="server"
    text="<center>Pick Products</center>"
    BackColor="white"
    ForeColor="Navy"
    Font-Bold="true"
    Font-Size="13"
    />
    <asp:RadioButtonList
    runat="server"
    id="rbl"
    CellPadding="4"
    CellSpacing="0"
    RepeatLayout="table"
    RepeatColumns="3"
    RepeatDirection="Vertical"
    AutoPostBack="true"
    OnSelectedIndexChanged="RadioButtonList_SelectedIndexChanged"
    font-size="10"
    BackColor="white"
    ForeColor="Navy"
    Font-Bold="true"
    width="100%"
    BorderWidth="1"
    BorderColor="Navy"
    />
    <p>
    <asp:label
    runat="server"
    id="lCheckBoxList"
    Font-Bold="false"
    Font-Size="8"
    ForeColor="Navy"
    />
</form>
</body>
</html>


We will get a page with three columns of RadioButton controls and a product name next to each when we execute this source code. The page is posted back to the server and the name of the product we selected is printed out to the screen when we select one. We can only check one product at a time when using the RadioButtonList control, unlike the CheckBoxList.

You might also like...

Comments

About the author

John Godel United States

John H. GODEL has an experience more than 22 years in the area of software development. He is a software engineer and architect. His interests include object-oriented and distributed computin...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Better train people and risk they leave – than do nothing and risk they stay.” - Anonymous