In this article I will explain with an example, how to populate (bind) DataList control using SqlDataSource in ASP.Net.
Here I am making use of Microsoft’s Northwind Database. The download and install instructions are provided in the following article.
DataList control and Repeat Layouts
The DataList control supports different Repeat Layouts
Table – This is the default layout. The Table layout renders the DataList as an HTML Table and its items are rendered inside the Table Cell. The number of Cells in each row can be set using the RepeatColumns property.
Flow – The Flow layout does not render the DataList as any HTML element. All the DataList items are rendered directly just as how the Repeater control repeats its items.
OrderedList and UnorderedList – The OrderedList and UnorderedList layouts renders the DataList as HTML Ordered List and Unordered List. But in .Net 4.0 and above these are no longer supported.
DataList control and Templates
The DataList control makes use of the following templates.
HeaderTemplate – The content of this template will not be repeated and will be placed in the top most position i.e. head section of the DataList control.
ItemTemplate – The content of this template will be repeated for each record present in its DataSource.
AlternatingItemTemplate – AlternatingItemTemplate is used for adding alternate items. It is used along with ItemTemplate, generally for displaying a different design for alternating items.
SeparatorTemplate - This template is used to add a separator between two items of the DataList control.
FooterTemplate – The content of this template will not be repeated and will be placed in the bottom most position i.e. footer section of the DataList control.
The following HTML Markup consists of an ASP.Net DataList control and ASP.Net SqlDataSource control.
The SqlDataSource control is set with the following properties.
1. ConnectionString – Name of the Connection String setting in the Web.Config file.
2. SelectCommand – The Select statement to fetch the records from the Customers table of the Northwind database.
The ID of the SqlDataSource control is set as DataSourceID of the DataList control.
<asp:DataList ID="dlCustomers" runat="server" DataSourceID="SqlDataSource1" RepeatColumns = "3" CellSpacing = "3" RepeatLayout = "Table">
<table class = "table">
<b><%# Eval("ContactName") %></b>
<%# Eval("City") %>,
<%# Eval("PostalCode") %><br />
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:constr %>"
SelectCommand="SELECT TOP 9 * FROM Customers"></asp:SqlDataSource>