This tutorial explains how to use asp:DataList control in asp .net.For this tutorial we are using NorthWnd database "Customer" table.
Data List Control and Templates:
1.HeaderTemplate
2.Item Template
3.AlternatingItemTemplate
4.Sepaerator Template
5.FooterTemplate
ConnectionString:
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=(local);Initial Catalog=NORTHWND;Integrated Security=SSPI;"/>
</connectionStrings>
Html and Asp Tag:
The following tag shows datalist with itemtemplate.
<asp:DataList ID="dlExample" runat="server">
<ItemTemplate>
<div class="w3-container">
<div class="w3-row">
<div class="w3-col m4">
<table width="600px" border="2" class="w3-table-all">
<tr class="w3-teal">
<td colspan="2">
<strong>Customert Details</strong>
</td>
</tr>
<tr>
<td>
<ul class="w3-ul">
<li><strong>Company Name:</strong><%# Eval("CompanyName") %></li>
<li><strong>Contact Name:</strong><%# Eval("ContactName") %></li>
<li><strong>Contact Title:</strong><%# Eval("ContactTitle") %></li>
</ul>
</td>
<td>
<strong>Address:</strong>
<br />
<%# Eval("Address") %>
</td>
</tr>
</table>
</div>
</div>
</div>
<br />
</ItemTemplate>
</asp:DataList>
Code Behind:
Following code bind datatable to asp datalist control.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDataList();
}
}
private void BindDataList()
{
try
{
string sConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(sConnectionString);
string sqlQuery = "Select top 5 *from Customers";
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
dlExample.DataSource = dt;
dlExample.DataBind();
}
catch (Exception ex)
{
Response.Write("<script>alert('Exception:'"+ex.Message+"</script>");
}
}
Output:
No comments:
Post a Comment