asp.net.ph

Skip Navigation Links

Adding DataList Controls to a Web Forms Page

Controls You Can Use on Web Forms   ASP.NET Data Controls   DataList Control


Essentially, to create a working DataList control, you need to add the control to the page and bind the control to a data source.

The below procedures show the minimum steps needed to display data in a DataList control.

To add a DataList control to a Web Forms page

This first example shows a DataList control that is bound to a SqlDataSource control.

  1. Declare an <asp:datalist> element on the page. For syntax, see DataList Control Syntax.
  2. Specify the control’s DataSourceID property.
  3. Optionally set the list’s base properties.
    <asp:datalist id="myList" runat="server"
       datasourceid="products"
       width="90%"
       cellpadding=10
       repeatcolumns=2 >
  4. Within the DataList declaration, declare an <ItemTemplate> element.
  5. Within the ItemTemplate, define each field from the data source that you intend to present.

    To display the value of a field in the ItemTemplate, use DataBinding Expression Syntax.

    <itemtemplate>
       <b>Product Code:</b> <%# Eval ( "ProductCode" ) %>
       <br>
       ...
       <b>Price:</b> <%# Eval ( "UnitPrice", "{0:c}" ) %>
    </itemtemplate>
Binding a DataList to a Data Source Control
Run Sample | View Source

NOTE: The ItemTemplate must contain at least one databinding expression that binds a control to a field from the data source; otherwise the DataList has nothing to render.

The DataSource property of a DataList can also be set programmatically, just like any Web server control property. Below shows an example of binding a data source to a DataList in code.

<script language="C#" runat="server">
   protected void Page_Load ( object src, EventArgs e ) {
      string query = "SELECT ProductType, ProductCode, ... FROM Products";
      myList.DataSource = fetchReader ( query, "dbtutor" );
      myList.DataBind ( );
   }
</script>
Binding a Data Source to a DataList Control
Run Sample | View Source

NOTE: To see actual examples of using a DataList in real-world scenarios, see our featured applications Books and more ... and Hotels and more .... Both applications demonstrate extensive use of the DataList in various configurations.

The above examples apply several concepts and methods that are described elsewhere in this workshop. For particulars, see ADO.NET Primer, Introduction to Data Binding in Web Forms, Web Forms Server Controls Templates.

If you intend to let users select and/or edit items in the DataList, you need to define a <SelectedItemTemplate> and/or an <EditItemTemplate> as well.

See Also

Specifying List Direction in a DataList Control   Specifying List Layout in a DataList Control



© 2025 Reynald Nuñez and asp.net.ph. All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note