Fun with DataLists – Twilight Zone Database

This Code Sample shows different methods of searching with DataLists – with Multiple LinkButtons (consolidated into one SubRoutine), and Dynamic searching with DropDownList and Textbox input. It also incorporates using a RequiredField Validator on the textbox search, and using CausesValidation=’false’ on the LinkButtons, so as not to cause validation when clicking the LinkButtons.

If you’d like to recreate this on your SQL Server – - you can download the sql script to recreate the table, along with the .CSV file with the data by clicking here.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.2">
	<title>Twilight Zone Seasons</TITLE>
<script language="VB" runat="server">
Dim sSeason as String
Dim sDesignation as String

Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
	dlsearchby.items.Add("Writer")
	dlsearchby.items.Add("Actor")
	dlsearchby.items.Add("Director")
	dlsearchby.items.Add("Title")
end if
End Sub

Sub GetSeason(Source as Object, E as EventArgs)
sDesignation=source.ID
	Select Case Source.ID
		Case "First"
			sSeason="1"
		Case "Second"
			sSeason="2"
		Case "Third"
			sSeason="3"
		Case "Fourth"
			sSeason="4"
		Case "Fifth"
			sSeason="5"
	End Select
	Dim strConn as string = "server=YourServer;uid=YourUID;pwd=YourPWD;database=YourDB"
	Dim MySQL as string = "Select * from Seasons Where Season = @season  Order by id"
	Dim MyConn as New SQLConnection(strConn)
	Dim objDR as SQLDataReader
	Dim Cmd as New SQLCommand(MySQL, MyConn)
	cmd.Parameters.Add(New SQLParameter("@season", sSeason))
	MyConn.Open()
	objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
	MyDataList.DataSource = objDR
	MyDataList.DataBind()
	MyDataList.visible="true"
	dlsearchby.selectedIndex=0
	txtSearch.text=""
	MyConn.Close
End Sub

Sub doSearch(Source as Object, E as EventArgs)
	Dim sSearchby as String
	MyDataList.visible="false"
	Dim strConn as string = "server=YourServer;uid=YourUID;pwd=YourPWD;database=YourDB"
	Dim MySQL as string = "Select * from Seasons where " & dlsearchby.selectedItem.text & _
	" Like ''%" & txtSearch.text & "%'' order by season"
	Trace.Warn("sql = " & MySQL)
	Dim MyConn as New SQLConnection(strConn)
	Dim objDR as SQLDataReader
	Dim Cmd as New SQLCommand(MySQL, MyConn)
	MyConn.Open()
	objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
	dlSearch.DataSource = objDR
	dlSearch.DataBind()
	MyConn.Close
dlSearch.visible="true"
End Sub
</script>

<STYLE TYPE="text/css">
<!--
BODY {
	background : #000000
	color : #FFFFFF
}
.doWhite {
	color : #FFFFFF
}
A:LINK {
	color : #FFFFFF
}
A:VISITED {
	color : #FFFFFF
}
-->
</STYLE>
</head>
<BODY>

<Form id="form1" runat="server">
<div align="center">
<b><font Size="5" Color="#FFFFFF">Twilight Zone DataBase</font></b>
<hr><b><i><font Color="#FFFFFF">Select Season:</font></i></b>
<asp:LinkButton id="First"
	cssClass="doWhite"
	CausesValidation="false"
	Text="1st Season"
	onclick="GetSeason" runat="server" />
<asp:LinkButton id="Second"
	cssClass="doWhite"
	CausesValidation="false"
	Text="2nd Season"
	onclick="GetSeason" runat="server" />
<asp:LinkButton id="Third"
	cssClass="doWhite"
	CausesValidation="false"
	Text="3rd Season"
	onclick="GetSeason" runat="server" />
<asp:LinkButton id="Fourth"
	cssClass="doWhite"
	CausesValidation="false"
	Text="4th Season"
	onclick="GetSeason" runat="server" />
<asp:LinkButton id="Fifth"
	cssClass="doWhite"
	CausesValidation="false"
	Text="5th Season"
	onclick="GetSeason" runat="server" /><hr>
<b><i><font Color="#FFFFFF">Search:</font></i></b>
<asp:DropDownList id="dlsearchby" runat="server" />
<asp:TextBox id="txtSearch" runat="server" />
<asp:Button id="btnSearch" Text="Search" onclick="doSearch" runat="server" /><br>
<asp:RequiredFieldValidator ID="vldSearch"
	ControlToValidate="txtSearch"
	Display="Dynamic" runat="server">
		You must include search criteria
</asp:RequiredFieldValidator><hr>
<asp:DataList runat="server"
	Id="MyDataList"
	GridLines="None"
	cellpadding="2"
	cellspacing="2"
	Headerstyle-BackColor="#000000"
	HeaderStyle-Forecolor="White"
	Headerstyle-Font-Name="Arial"
	Headerstyle-Font-Size="8"
	BackColor="#000000"
	Forecolor="White"
	Font-Name="Arial"
	Font-Size="10">
<HeaderTemplate>
	<font Color="#FFFFFF">
	<b><i><font Size="4"><%# sDesignation%> Season</font></i></b>
	</font><br>
</HeaderTemplate>
	<ItemTemplate>
		<font Color="#FFFFFF"><b><%# Container.DataItem("Title")%></b><br>
		<b>Writer: </b><%# Container.DataItem("Writer")%><br>
		<b>Director: </b><%# Container.DataItem("Director")%><br>
		<b>Show Summary: </b><br>
		<%# Container.DataItem("Notes")%><br>
		<b>Cast :</b><br>
		<%# Container.DataItem("Actor")%></font><p>
		</ItemTemplate>
</ASP:DataList>

<asp:DataList runat="server"
	Id="dlSearch"
	GridLines="None"
	cellpadding="2"
	cellspacing="2"
	Headerstyle-BackColor="#000000"
	HeaderStyle-Forecolor="White"
	Headerstyle-Font-Name="Arial"
	Headerstyle-Font-Size="8"
	BackColor="#000000"
	Forecolor="White"
	Font-Name="Arial"
	Font-Size="10"
	Width="100%">
	<HeaderTemplate>
		<font Color="#FFFFFF">
		<b><i><font Size="4">Search Results </font></i></b>
		</font><br>
	</HeaderTemplate>
	<ItemTemplate>
		<font Color="#FFFFFF"><b>Season : </b><%# Container.DataItem("season")%><br>
		<b><%# Container.DataItem("Title")%></b><br>
		<b>Writer: </b><%# Container.DataItem("Writer")%><br>
		<b>Director: </b><%# Container.DataItem("Director")%><br>
		<b>Show Summary: </b><br>
		<%# Container.DataItem("Notes")%><br>
		<b>Cast :</b><br>
		<%# Container.DataItem("Actor")%></font><p>
	</ItemTemplate>
</ASP:DataList>
<b><i><font Color="#FFFFFF"><asp:Label ID="label1"  runat="server" /></font></i></b></div>
</Form>
</body>
</html>

Using Validators with Panels, Separating Form Sections

This code sample takes a previous code sample, ‘Using Panels to Separate Form Sections’ and enhances it, using three of the built in Validators of DotNet, the Required Field Validator, the Regular Expression Validator and the Compare Validator. Most of the fields use the Required Field Validator, but the Password verification in the last panel uses the Compare Validator, like many forms online do these days and the US Zip Code uses the Regular Expression Validator.

Luckily, the validation scenario works very will with Panels, as you will see when you try the live sample.

ListBox – Select All/Select None

This code sample takes another code sample on the site (2 Listboxes – Moving Items From One to Another) and enhances it. Here, we also show how to add ‘Select All/Select None’ functionality for each listbox.

<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.0">
	<title>ListBox - Select All/Select None</TITLE>
	<Link REL=STYLESHEET HREF="/basicArial.css" TYPE="text/css">

<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
        If Not Page.IsPostBack Then
            Dim intFirst As Integer
            For intFirst = 1 To 10
                ListBox1.Items.Add("Item " & intFirst)
            Next
        End If
End Sub

Sub button1_click(Source as Object, E as EventArgs)
        Dim li As ListItem
        For Each li In ListBox1.Items
            If li.Selected = True Then
                ListBox2.Items.Add(li.Text)
            End If
        Next

        Dim counter As Integer
        For counter = (ListBox1.Items.Count - 1) To 0 Step -1
            If ListBox1.Items(counter).Selected = True Then
                ListBox1.Items.RemoveAt(counter)
            End If
       Next
End Sub

Sub button2_click(Source as Object, E as EventArgs)
        Dim counter As Integer
        Dim li As ListItem

        For Each li In ListBox2.Items
            If li.Selected = True Then
                ListBox1.Items.Add(li.Text)
            End If
        Next

        For counter = (ListBox2.Items.Count - 1) To 0 Step -1
            If ListBox2.Items(counter).Selected = True Then
                ListBox2.Items.RemoveAt(counter)
            End If
        Next
End Sub
Sub selAll(Source as Object, E as EventArgs)
	Dim liAll As ListItem
	Dim sList as ListBox
	if Source.id="lbSelectAll" then
		sList=ListBox1
	else
		sList=ListBox2
	End If
        	For Each liAll In sList.Items
	liAll.Selected=true
        Next
End Sub
Sub selNone(Source as Object, E as EventArgs)
        	Dim liAll As ListItem
	Dim sList as ListBox
	if Source.id="lbSelectNone" then
		sList=ListBox1
	else
		sList=ListBox2
	End If
        For Each liAll In sList.Items
	liAll.Selected=false
        Next
End Sub

</script>
</head>
<body>
<div align="center"><Form id="form1" runat="server">
<table  cellpadding="2" cellspacing="2" border=0>
	<tr>
		<td align="center" valign="top">
<asp:ListBox id="ListBox1"
width="125px" height="175"
SelectionMode="Multiple" runat="server" /><br>
Select : <asp:LinkButton id="lbSelectAll"
Text="All" onclick="SelAll" runat="server" />
<asp:LinkButton id="lbSelectNone" Text="None" onclick="selNone" runat="server" /></td>
		<td align="center" valign="center">
<asp:Button id="button1"
width="88px" height="26"
Text="Add >>" onclick="button1_click" runat="server" /><br>
<asp:Button id="button2"
Text="<< Remove" onclick="button2_click"
width="88px" height="26" runat="server" />
		</td>
		<td align="center" valign="top">
<asp:ListBox id="Listbox2" width="125px" height="175"
SelectionMode="Multiple" runat="server" /><br>
Select : <asp:LinkButton id="lb2SelectAll"
Text="All" onclick="SelAll" runat="server" />
<asp:LinkButton id="lb2SelectNone" Text="None" onclick="selNone" runat="server" /></td>
	</tr>
</table>

</Form></div>
</body>
</html>

Simple Scrollable DataGrid

Here’s perhaps the simplest way to add scroll-ability to your DataGrid. It’s accomplished by adding your DataGrid inside DIV tags, with overflow set to scroll. You’ll probably need to fool around with the width and height for your particular uses, but it’s pretty cool little trick I found in several places, including the ASP.Net/forums. It boils down to these two facts:
If you assign the width of the Div smaller than the DataGrid, you automatically have horizontal scroll bars.
If you make the height of the Div smaller than the height of the DataGrid, then you automatically have vertical scrollbars.

This sample uses the SQL Server managed provider and the Northwind Database with the Products Table. In order to try this on your system, just copy the code directly from the page, paste it into a new page on your computer, change the connection string to match your system and you’re on your way.

To try this with the OleDb managed provider, copy the code and pasted it into our Database Code Conversion Tool before you do the steps listed in the last paragraph.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.2">
	<title>Simple Scrollable DataGrid</title>
<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
	Dim strConn as string = "server=YourServer;uid=YourUID;pwd=YourPWD;database=Northwind"
	Dim MySQL as string = "Select Products.ProductName, Products.QuantityPerUnit, " & _
"Products.UnitPrice, Products.UnitsInStock from Products"
	Dim MyConn as New SQLConnection(strConn)
	Dim objDR as SQLDataReader
	Dim Cmd as New SQLCommand(MySQL, MyConn)
	MyConn.Open()
	objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
	MyDataGrid.DataSource = objDR
	MyDataGrid.DataBind()
End Sub
</script>
</head>
<body>
<div id="Layer1" style="position:relative;width:450px; height:300px;overflow: scroll;">
<form runat="server" method="post">
<asp:Datagrid runat="server"
	Id="MyDataGrid"
	GridLines="Both"
	cellpadding="0"
	cellspacing="0"
	Headerstyle-BackColor="#8080C0"
	Headerstyle-Font-Name="Arial"
	Headerstyle-Font-Bold="True"
	Headerstyle-Font-Size="12"
	BackColor="#8080FF"
	Font-Name="Arial"
	Font-Size="10"
	AlternatingItemStyle-BackColor="#DFDFDF"
	AlternatingItemStyle-Font-Name="Arial"
	AlternatingItemStyle-Font-Size="10"
	BorderColor="Black"
	AutogenerateColumns="False">
	<Columns>
		<asp:BoundColumn
			DataField="ProductName"
			HeaderText="ProductName">
		</asp:BoundColumn>
		<asp:BoundColumn
			DataField="QuantityPerUnit"
			HeaderText="QuantityPerUnit">
		</asp:BoundColumn>
		<asp:BoundColumn
			DataField="UnitPrice"
			HeaderText="UnitPrice">
		</asp:BoundColumn>
		<asp:BoundColumn
			DataField="UnitsInStock"
			HeaderText="UnitsInStock">
		</asp:BoundColumn>
	</Columns>
</asp:DataGrid>

</form>
</div>
</body>
</html>

Enhanced Calendar/Database with MS Access

This is the same calendar code as that posted earlier, using SQL Server. However, this time, it was run through the Database Code Converter Tool on the ASPNet101.com site to convert it from the SQL Server Managed Provider to the OleDb Managed Provider.

To download the zipped MS Access Database to work with this, Download Here. Then, to get this working on your system, just copy this code to a new file on your computer, change the connection string to match the path on your computer.

DataReader Alternative – Check for Empty

Using Record Count to Test for Empty Results

There is another code sample on this site to test an empty DataReader before displaying results (Check for Empty), however, this is an alternative which will ONLY work, apparently with SQL Server. It uses two SQL statements, separated by a semi-colon to get two result sets. Then, it uses the NextResult and GetValue methods to accomplish the goal of checking for the empty DataReader, before displaying results, by checking for a RowCount first. If the number of records returned is larger than ’0′, then it’s displayed. Otherwise, a message is displayed “Sorry – no records exist with the last name of …

Thanks go to Bipin Joshi for the inspiration for this code sample. I saw his record count article and realized this could be used as an Empty DataReader check also.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.2">
	<title>Using Record Count to Test for Empty Results</title>
<script language="VB" runat="server">
Dim strConn as String="server=YourServer;uid=YourUID;pwd=YourPwd;database=Northwind"
Sub GetRecord(Source as Object, E as EventArgs)
	ph1.visible="true"
	label1.text=""
	Dim MySQL as string = "Select Count(*) from Employees Where LastName =  " & _
	"@LName;Select FirstName, LastName, Title, Address, City, Region, PostalCode, " & _
	"HomePhone from Employees Where LastName =  @LName"
	Dim MyConn As SqlConnection = New SqlConnection(strConn)
	MyConn.Open()
	Dim objDR as SQLDataReader
	Dim Cmd as New SQLCommand(MySQL, MyConn)
	cmd.Parameters.Add(New SQLParameter("@LName", text1.text))
	cmd.Connection=MyConn
	objDR=Cmd.ExecuteReader
	objDR.Read()
	Dim intVal as Integer
	intVal=objDR.GetValue(0)
	label1.text=intVal & " Record Matched your query"
	if intVal >0 then
		MyDataGrid.Visible="true"
		objDR.NextResult()
		MyDataGrid.DataSource = objDR
		MyDataGrid.DataBind()
	else
		MyDataGrid.Visible="false"
		label1.text="Sorry - no records exist with the last name of " & text1.text
	End If
	MyConn.Close
End Sub
</script>

</head>
<body>

<Form id="form1" runat="server">
Search Employees Here: (Use Last Name)
<asp:TextBox
id="text1"
runat="server" />
<asp:Button
id="button1"
Text="Get Employee Details"
onclick="GetRecord" runat="server" /><br>
<i><b><font Color="#FF0000" size="2">(Hint - Try ''Davolio'', ''Fuller'', ''King'', ''Peacock'' for valid names) </font></b></i>

<asp:placeholder ID="ph1"  runat="server" Visible="false">
<hr>
<asp:Datagrid runat="server"
	Id="MyDataGrid"
	GridLines="Both"
	cellpadding="2"
	Headerstyle-BackColor="#8080C0"
	Headerstyle-Font-Name="Arial"
	Headerstyle-Font-Size="14"
	Headerstyle-Font-Bold="true"
	BackColor="#8080FF"
	Font-Name="Arial"
	Font-Size="11"
	BorderColor="Black">
</asp:DataGrid>
<asp:Label ID="label1" runat="server" />
</asp:placeholder>
</Form>
</body>
</html>

Using Template Columns to Consolidate Fields

At times, we would like the basic structure of a DataGrid, but don’t really want every field in the database table to be in its own separate column, for aesthetic purposes.

This sample uses the SQL managed provider, and the Employees table of the Northwind database to show how Template Columns in a DataGrid may be used to accomplish this task.

To do this on your own computer, just copy the code into a new ASP.Net page, and change the provider string to match your system’s needs. If you don’t have SQL Server, copy the database code to our Database Code Conversion Tool, change it over to the OleDb version, then change your provider string.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.2">
	<title>Using Template Columns to Consolidate Fields</title>
<script language="VB" runat="server">
Dim strConn as string = "server=YourServer;uid=YourUID;pwd=Your PWD;database=Northwind"
Sub Page_Load(Source as Object, E as EventArgs)
	Dim MySQL as string = "Select FirstName, LastName, Title, BirthDate from Employees"
	Dim MyConn as New SQLConnection(strConn)
	Dim ds as DataSet=New DataSet()
	Dim Cmd as New SQLDataAdapter(MySQL,MyConn)
	Cmd.Fill(ds,"Employees")
	MyDataGrid.Datasource=ds.Tables("Employees").DefaultView
	MyDataGrid.DataBind()
End Sub
</script>
</head>
<body>
<form runat="server" method="post">
<div align="center">
<asp:Datagrid runat="server"
	Id="MyDataGrid"
	GridLines="both"
	Headerstyle-BackColor="#8080C0"
	Headerstyle-Font-Name="Arial"
	Headerstyle-Font-Size="14"
	Headerstyle-font-bold="true"
	Font-Name="Arial"
	Font-Size="10"
	BorderColor="Black"
	autogeneratecolumns="false">
	<columns>
		<asp:TemplateColumn HeaderText="Name and Information">
			<ItemTemplate>
			<%#Container.DataItem("firstname")%> <%#Container.DataItem("lastname")%>
			(<%# formatdatetime(Container.DataItem("Birthdate"),vbshortdate)%>),
			<b><%#Container.DataItem("title")%></b>
			</ItemTemplate>
		</asp:TemplateColumn>
	</columns>
</asp:DataGrid></div>
</form>
</body>
</html>

Adding Dynamic Controls to ASP.Net Pages

Sometimes we need to add controls to a page dynamically. For instance, let’s say we have registered users at your site. Each one has an option on the way a choice is to be displayed to him/her (RadioButtons, ListBox, DropDownList, etc). This code sample shows exactly that. It uses Arraylists for the selection list, but it could just as easily be retrieved from a database table also, and bound to the controls.

<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.2">
	<title>Adding Dynamic Controls</title>
<script language="VB" runat="server">
Dim sCtrl as String
Dim alNewList as ArrayList
Dim ctrlList as ArrayList

Sub Page_Load(Source as Object, E as EventArgs)

if not Page.IsPostBack then
	ctrlList=New Arraylist
	ctrlList.add("DropDownList")
	ctrlList.add("CheckBoxList")
	ctrlList.add("RadioButtonList")
	ctrlList.add("ListBox")

	rbl.DataSource=ctrlList
	rbl.DataBind
	rbl.SelectedIndex=0
end if
	alNewList=New Arraylist
	alNewList.add("Blue")
	alNewList.add("Red")
	alNewList.add("Green")
	alNewList.add("Orange")
	alNewList.add("Pink")
End Sub

Sub GetControl(Source as Object, E as EventArgs)
sCtrl= rbl.selecteditem.text
	if sCtrl <> "" then
		Select Case sCtrl
			Case "RadioButtonList"
				Dim objRadio As New RadioButtonList
				objRadio.DataSource=alNewList
				objRadio.databind
				ph1.Controls.Add(objRadio)
				objRadio.SelectedIndex=1
			Case "DropDownList"
				Dim objDDL As New DropDownList
				objDDL.DataSource=alNewList
				objDDL.databind
				ph1.Controls.Add(objDDL)
				objDDL.SelectedIndex=0
			Case "CheckBoxList"
				Dim objCBL As New CheckBoxList
				objCBL.DataSource=alNewList
				objCBL.databind
				ph1.Controls.Add(objCBL)
				objCBL.SelectedIndex=2
			Case "ListBox"
				Dim objLB As New CheckBoxList
				objLB.DataSource=alNewList
				objLB.databind
				ph1.Controls.Add(objLB)
				objLB.SelectedIndex=3
		End Select
	end if
End Sub
Sub clearSelection(Source as Object, E as EventArgs)
	sCtrl=""
End Sub
</script>
</head>
<body>

<Form id="form1" runat="server">
<table>	<tr>
		<td align="Left" valign="Top"><b>Choose Control Type</b>:<br>
			<asp:RadioButtonList id="rbl" runat="server">
			</asp:RadioButtonList>
			<asp:Button id="button1"
			Text="Get New Control"
			onclick="GetControl" runat="server" />

			<asp:Button id="button2"
			Text="Clear Selection"
			onclick="clearSelection"
			runat="server" />
		</td>
		<td align="Left" valign="Top">&nbsp; &nbsp; &nbsp; &nbsp; </td>
		<td align="Left" valign="Top">
			<asp:placeholder ID="ph1"  runat="server"></asp:placeholder>
		</td>
	</tr>
</table>
</Form>
</body>
</html>

3 Ways to Display a Dataset in a Web Page

When we first start using ASP.Net, many people first start working with a DataGrid due to its apparent ‘on the surface’ simplicity. Of course as learning progresses, we find out just how powerful it really is. Also, we learn about the DataSet and how to make it the DataSource of the DataGrid. However, many times, other methods of displaying the results in the DataSet are overlooked even though the DataGrid is not exactly what’s needed.

This code sample uses the SQL Managed Provider (Employees table in the Northwind database) to show 2 other ways to display the results from a DataSet (a DataList and assigning the data to a variable then, using a server control’s text property to display the records however we need.

To use this on your local computer, just copy the code below to a new page on your system. Then, change the connection string to your database. If you are using MS Access, just copy the code to the DataBase Code Conversion Tool on this web site.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>

<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.2">
	<title>3 Ways to Display a DataSet</title>
<script language="VB" runat="server">
Dim sEmps as String
Dim strConn as string = "server=YourServer;uid=YourUID;pwd=YourPWD;database=NorthWind"
Sub Page_Load(Source as Object, E as EventArgs)
	Dim MySQL as string = "Select Employees.FirstName, Employees.LastName, Employees.Title, " & _
	"Employees.BirthDate from Employees"
	Dim MyConn as New SQLConnection(strConn)
	Dim ds as DataSet=New DataSet()
	Dim Cmd as New SQLDataAdapter(MySQL,MyConn)
	Cmd.Fill(ds,"Employees")

	''These next 2 lines assign the data in the dataset to the Datalist (MyDataList)
	MyDataList.Datasource=ds.Tables("Employees").DefaultView
	MyDataList.DataBind()

	''These lines assign the data to a variable, which is then assigned to the text property of a literal control(litEmps)
	Dim dr As DataRow
	For Each dr In ds.Tables("Employees").Rows
		sEmps+="<b>" & dr("firstname") & " " & dr("lastname") & " </b> - " & dr("Title") & "<br>"
	Next
	litEmps.text=sEmps

	''then, here we assign the data to a DataGrid, much like the way we did in the example for the DataList:
	MyDataGrid.Datasource=ds.Tables("Employees").DefaultView
	MyDataGrid.DataBind()
End Sub
</script>
</head>
<body>

<Form id="form1" runat="server">
<div align="center"><table>	<tr>
		<td align="Left" valign="Top"><b><i><font Color="#0000FF">Using a DataList:</font></i></b>
	<asp:DataList runat="server"
		Id="MyDataList"
		GridLines="None"
		cellpadding="2"
		cellspacing="2"
		Headerstyle-BackColor="#8080C0"
		Headerstyle-Font-Name="Arial"
		Headerstyle-Font-Size="8"
		Font-Name="Arial"
		Font-Bold="false"
		Font-Size="8">
		<ItemTemplate>
		<%# DataBinder.Eval(Container.DataItem, "firstname") %>
		<%# DataBinder.Eval(Container.DataItem, "lastname") %>
		 - <b><i><%# DataBinder.Eval(Container.DataItem, "Title") %> </i></b>
	</ItemTemplate>
	</ASP:DataList>
		</td>
		<td align="Left" valign="Top"><b><i><font Color="#0000FF">Using a variable:</font></i></b><br>
<asp:Literal ID="litEmps" runat="server"></asp:literal></td>
	</tr>
	<tr>
		<td align="center" valign="Top" Colspan="2"><hr>
	<b><i><font Color="#0000FF">Using a DataGid:</font></i></b>
	<asp:Datagrid runat="server"
		Id="MyDataGrid"
		GridLines="Both"
		cellpadding="0"
		cellspacing="0"
		Headerstyle-BackColor="#8080C0"
		Headerstyle-Font-Name="Arial"
		Headerstyle-Font-Size="12"
		Headerstyle-Font-Bold="true"
		BackColor="#8080FF"
		Font-Name="Arial"
		Font-Size="10"
		AlternatingItemStyle-BackColor="#CFCFCF"
		AlternatingItemStyle-Font-Name="Arial"
		AlternatingItemStyle-Font-Size="8"
		BorderColor="Black">
	</asp:DataGrid>
		</td>
	</tr>
</table></div>
</Form>
</body>
</html>

Populating/Binding a DataList with a DataReader

This code sample uses the SQL Server Managed Provider to bind a DataList with a DataReader, showing only certain columns/fields from the table. It uses the Employees table of the Northwind Database. Also, it shows how you can use the Repeatcolumns property and Templates (both Header and Item Templates) to format the data on the page and block or show certain fields in the table.

To use this on your system, all you need to do is copy the code directly to a new page and change the connection string to match your needs on your system. Also, if you have MS Access, instead of SQL Server, be sure to visit our DataBase Code Conversion Tool to convert the SQL Server items to OleDb.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.2">
	<title>Populating a DataList with a DataReader</title>
<script language="VB" runat="server">
Dim strConn as String
Sub Page_Load(Source as Object, E as EventArgs)
	strConn  = "server=YourServer;uid=YourUID;pwd=YourPWD;database=YourDB"
	Dim MySQL as string = "Select FirstName, LastName, Title, BirthDate from Employees Order by LastName"
	Dim MyConn as New SQLConnection(strConn)
	Dim objDR as SQLDataReader
	Dim Cmd as New SQLCommand(MySQL, MyConn)
	MyConn.Open()
	objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
	MyDataList.DataSource = objDR
	MyDataList.DataBind()
End Sub
</script>
</head>
<body>
<Form id="form1" runat="server">
<asp:DataList runat="server"
	Id="MyDataList"
	GridLines="None"
	cellpadding="2"
	cellspacing="2"
	Font-Name="Arial"
	Headerstyle-BackColor="#E0E0E0"
	Headerstyle-Font-Name="Arial"
	Headerstyle-Font-Bold="True"
	Headerstyle-Font-Size="14"
	Headerstyle-HorizontalAlign="Center"
	Font-Size="10"
	RepeatColumns="3"
	Width="100%">
	<HeaderTemplate>
Employee Names/Birthdates
	</HeaderTemplate>
	<ItemTemplate>
		<b>Name: </b><%# Container.DataItem("FirstName")%> <%# Container.DataItem("LastName")%><br>
		<b>Title: </b><%# Container.DataItem("Title")%><br>
		<b>BirthDate: </b><%# formatdatetime(Container.DataItem("BirthDate"),vbshortdate)%><p>
	</ItemTemplate>
</ASP:DataList>
</Form>
</body>
</html>