In this post, you are going to learn how to use ASP.Net DataList control as well as demonstrate binding of data to this control. You can as well download the complete app using Download File link Button
The ASP.NET DataList control is a light weight server side control that works as a container for data items. It is used to display list of repeated items or data.
It displays data from the data source. The data source can be either a DataTable or a table from database.
The DataList control has five templates such as;
- HeaderTemplate: Use to displays Header text for a Data Source collection and applies a different style for the Header text.
- AlternatingItemTemplate: It is used to change the background color or style of alternating items in a Data Source collection.
- Itemtemplate: This template defines how the each item is rendered from the Data Source collection.
- SeperatorTemplate: This template is used to determine the separator element that separates each item in the item collection.
- FooterTemplate: This displays a footer element for the Data Source collection.
With the above little explanation, you must have understands what DataList control is and its various templates.
Let us create a simple application that will bind data to a DataList control and displayed them as well.
If you are looking for how to use repeater control then check
how to use asp.net repeater control
For this tutorial, you should create a Microsoft Access database with following specifications.
Database name: dbInfo
Table name: tblInfo
If you don't know how to create database then check
how to create database in Microsoft Access
Field Names |
Data Types |
pName |
Text |
Gender |
Text |
Country |
Text |
Course |
Text |
Now that you have created the database, you should also create the website.
Below is the HTML source
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
Name<br />
<asp:TextBox ID="txtname" runat="server"></asp:TextBox>
</td>
<td>Gender
<asp:DropDownList ID="drpgender" runat="server">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>
</asp:DropDownList></td>
</tr>
<tr>
<td>
Country<br />
<asp:TextBox ID="txtcountry" runat="server"></asp:TextBox>
</td>
<td>
<asp:DropDownList ID="drpcourse" runat="server">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>Computer Science</asp:ListItem>
<asp:ListItem>Electrical Electronics</asp:ListItem>
<asp:ListItem>Telecommunications</asp:ListItem>
</asp:DropDownList></td>
</tr>
<tr>
<td>
<asp:Button ID="btnsubmit" runat="server" Text="Submit Details" /></td>
</tr>
</table>
<br />
<asp:Label ID="lblstatus" Visible="false" runat="server" Text="Label"></asp:Label><br />
<table >
<tr style="background-color:#0094ff;color:#fff; width:100%">
<td>Name
<td>Gender
<td>Country
<td>Course
</tr>
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<tr style="background-color:dimgray;color:#fff; width:100%">
<td><%# Eval("pname")%>
<td><%# Eval("gender")%>
<td><%# Eval("country")%>
<td><%# Eval("course")%>
</tr>
</ItemTemplate>
</asp:DataList>
</table>
</div>
</form>
</body>
</html>
In the codebehind, Import the following Namespaces
Imports System.Data
Imports System.Data.OleDb
Then add this to the General Declaration section
Dim con As New OleDb.OleDbConnection '("Provider=Microsoft.Jet.OleDb.4.0; Data Source='" & Server.MapPath("/db/dbInfo.mdb") & "'")
Double click on the btnsubmit and type the following or paste the codes
Protected Sub btnsubmit_Click(sender As Object, e As EventArgs) Handles btnsubmit.Click
Dim cmd As New OleDb.OleDbCommand
Try
con.ConnectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source='" & Server.MapPath("/db/dbInfo.mdb") & "'"
con.Open()
cmd.CommandText = "INSERT INTO tblinfo(pname,country,gender,course)VALUES(@pname,@country,@gender,@course)"
cmd.Connection = con
cmd.Parameters.AddWithValue("@pname", txtname.Text)
cmd.Parameters.AddWithValue("@country", txtcountry.Text)
cmd.Parameters.AddWithValue("@gender", drpgender.Text)
cmd.Parameters.AddWithValue("@course", drpcourse.Text)
cmd.ExecuteReader()
Finally
cmd.Dispose()
con.Dispose()
Response.Redirect(Request.Url.AbsoluteUri)
End Try
End Sub
Create a procedure called BindInfoToDataList as follows
Sub BindInfoToDataList()
Dim cmd As New OleDb.OleDbCommand
Try
con.ConnectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source='" & Server.MapPath("/db/dbInfo.mdb") & "'"
con.Open()
cmd.CommandText = "SELECT*FROM tblinfo"
cmd.Connection = con
DataList1.DataSource = cmd.ExecuteReader()
DataList1.DataBind()
Catch ex As Exception
ScriptManager.RegisterStartupScript(Page, Page.GetType, "1111", "alert('Error occured');", True)
Finally
cmd.Dispose()
con.Dispose()
End Try
End Sub
Now that you have created the BindInfoToDataList procedure, you need to call this subroutine on page load event
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
BindInfoToDataList()
End Sub
And the following code to the DataList1 pre_render event to show count of total records saved
Protected Sub DataList1_PreRender(sender As Object, e As EventArgs) Handles DataList1.PreRender
If DataList1.Controls.Count <= 0 Then
lblstatus.Text = "No records saved yet"
lblstatus.ForeColor = Drawing.Color.Red
lblstatus.Visible = True
Else
lblstatus.Text = "Total records: " & DataList1.Controls.Count
lblstatus.ForeColor = Drawing.Color.Green
lblstatus.Visible = True
End If
End Sub
And the output is below
And the complete codebehind is below
Imports System.Data
Imports System.Data.OleDb
Partial Class _Default
Inherits System.Web.UI.Page
Dim con As New OleDb.OleDbConnection '("Provider=Microsoft.Jet.OleDb.4.0; Data Source='" & Server.MapPath("/db/dbInfo.mdb") & "'")
Protected Sub btnsubmit_Click(sender As Object, e As EventArgs) Handles btnsubmit.Click
Dim cmd As New OleDb.OleDbCommand
Try
con.ConnectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source='" & Server.MapPath("/db/dbInfo.mdb") & "'"
con.Open()
cmd.CommandText = "INSERT INTO tblinfo(pname,country,gender,course)VALUES(@pname,@country,@gender,@course)"
cmd.Connection = con
cmd.Parameters.AddWithValue("@pname", txtname.Text)
cmd.Parameters.AddWithValue("@country", txtcountry.Text)
cmd.Parameters.AddWithValue("@gender", drpgender.Text)
cmd.Parameters.AddWithValue("@course", drpcourse.Text)
cmd.ExecuteReader()
Finally
cmd.Dispose()
con.Dispose()
Response.Redirect(Request.Url.AbsoluteUri)
End Try
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
BindInfoToDataList()
End Sub
Sub BindInfoToDataList()
Dim cmd As New OleDb.OleDbCommand
Try
con.ConnectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source='" & Server.MapPath("/db/dbInfo.mdb") & "'"
con.Open()
cmd.CommandText = "SELECT*FROM tblinfo"
cmd.Connection = con
DataList1.DataSource = cmd.ExecuteReader()
DataList1.DataBind()
Catch ex As Exception
ScriptManager.RegisterStartupScript(Page, Page.GetType, "1111", "alert('Error occured');", True)
Finally
cmd.Dispose()
con.Dispose()
End Try
End Sub
Protected Sub DataList1_PreRender(sender As Object, e As EventArgs) Handles DataList1.PreRender
If DataList1.Controls.Count <= 0 Then
lblstatus.Text = "No records saved yet"
lblstatus.ForeColor = Drawing.Color.Red
lblstatus.Visible = True
Else
lblstatus.Text = "Total records: " & DataList1.Controls.Count
lblstatus.ForeColor = Drawing.Color.Green
lblstatus.Visible = True
End If
End Sub
End Class
That is all. Thanks for reading