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.
This first example shows a DataList control that is bound to a SqlDataSource control.
- Declare an <
asp:datalist
> element on the page. For syntax, see DataList Control Syntax.
- Specify the control’s DataSourceID property.
- Optionally set the list’s base properties.
<asp:datalist id="myList" runat="server"
datasourceid="products"
width="90%"
cellpadding=10
repeatcolumns=2 >
- Within the DataList declaration, declare an <ItemTemplate> element.
- 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>
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>
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.
Specifying List Direction in a DataList Control Specifying List Layout in a DataList Control