Delete from Database Using a DataGrid

This sample shows how to add a ‘Delete’ button to a datagrid in order to delete table records and uses a replica of the same table in our Insert and Update/Edit samples (SQL Server Managed Provider). It simply contains an autonumbering ID field, a Firstname field and a Lastname field.

To change this for MS Access useage, merely change the SQL references to OleDb references. And, as always, to use this on your own system, copy the code below to your own, new page, and just change the database references to match your system.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<!-- Created: 11/9/2002 12:55:10 PM -->
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.1">
	<title>Deleting from DataBase using a DataGrid</title>
<script language="VB" runat="server">
Sub MyDataGrid_DeleteCommand(s As Object, e As DataGridCommandEventArgs )
	Dim strConn as String = "server=YourServer;uid=YourUID;pwd=YourPWD;database=YourDB"
	Dim DeleteCmd As String = "DELETE from safetable Where id = @Id"
	Dim MyConn as New SQLConnection(strConn)
	Dim Cmd as New SqlCommand(DeleteCmd, MyConn)
	Cmd.Parameters.Add(New SqlParameter("@ID", MyDataGrid.DataKeys(CInt(e.Item.ItemIndex))))
	MyConn.Open()
	Cmd.ExecuteNonQuery()
	MyConn.Close()
	BindData
End Sub

Sub Page_Change(sender As Object, e As DataGridPageChangedEventArgs)
	MyDataGrid.CurrentPageIndex = e.NewPageIndex
	BindData
End Sub

Sub Page_Load(Source As Object, E As EventArgs)
	If Not Page.IsPostBack Then
		BindData()
	End If
End Sub

Sub BindData()
	Dim strConn as String = "server=YourServer;uid=YourUID;pwd=YourPWD;database=YourDB"
	Dim MySQL as string = "Select * from safetable Order by id desc"
	Dim MyConn as New SQLConnection(strConn)
	Dim ds as DataSet=New DataSet()
	Dim Cmd as New SQLDataAdapter(MySQL,MyConn)
	Cmd.Fill(ds,"safetable")
	MyDataGrid.Datasource=ds.Tables("safetable").DefaultView
	MyDataGrid.DataBind()
End Sub
</script>
</head>
<body>
<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="14"
	BackColor="#8080FF"
	Font-Name="Arial"
	Font-Size="11"
	AlternatingItemStyle-BackColor="#C0C0C0"
	AlternatingItemStyle-Font-Name="Arial"
	AlternatingItemStyle-Font-Size="11"
	BorderColor="Black"
	AllowPaging = "True"
	PageSize = "8"
	PagerStyle-Mode = "NumericPages"
	PagerStyle-HorizontalAlign="Center"
	PagerStyle-PageButtonCount = "10"
	OnPageIndexChanged = "Page_Change"
	AutogenerateColumns="False"
	OnDeleteCommand="MyDataGrid_DeleteCommand"
	DataKeyField="id"
	Width="50%">
	<Columns>
		<asp:ButtonColumn Text="Delete" HeaderText="Delete" CommandName="Delete"></asp:ButtonColumn>
		<asp:BoundColumn DataField="fname" HeaderText="fname"></asp:BoundColumn>
		<asp:BoundColumn DataField="lname" HeaderText="lname"></asp:BoundColumn>
	</Columns>
</asp:DataGrid>
</form>

For MS Access, just change the two data related subs to:
Sub MyDataGrid_DeleteCommand(s As Object, e As DataGridCommandEventArgs )
	 Dim strConn as String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & server.mappath("\pathAndNameToYourDB.mdb") & ";"
	 Dim DeleteCmd As String = "DELETE from safetable Where id = @Id"
	 Dim MyConn as New OleDbConnection(strConn)
	 Dim Cmd as New OleDbCommand(DeleteCmd, MyConn)
	 Cmd.Parameters.Add(New OleDbParameter("@ID", MyDataGrid.DataKeys(CInt(e.Item.ItemIndex))))
	 MyConn.Open()
	 Cmd.ExecuteNonQuery()
	 MyConn.Close()
	 BindData
End Sub

Sub BindData()
	Dim strConn as String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & server.mappath("\pathAndNameToYourDB.mdb") & ";"
	Dim MySQL as string = "Select * from safetable Order by id desc"
	Dim MyConn as New OleDbConnection(strConn)
	Dim ds as DataSet=New DataSet()
	Dim Cmd as New OleDbDataAdapter(MySQL,MyConn)
	Cmd.Fill(ds,"safetable")
	MyDataGrid.Datasource=ds.Tables("safetable").DefaultView
	MyDataGrid.DataBind()
End Sub

Updating/Editing a Chosen DataBase Record

Anyone who has had any dealings with databases knows there are several things which are needed:
Selecting Records
Inserting New Records
Deleting Records
Updating/Editing Recordsh

This code sample shows two things – Selecting Records, and then, choosing one record to then Update/Edit. It’s based on an earlier code sample (Populating a Form’s TextBoxes from a DB Query)

What you will see added here, is a very simple subroutine called ‘doUpdate’, which makes a connection to the database and performs a very simple Update SQL statement. There are only three fields in this simple table (ID, fname and lname). The ID field is an autonumbering/Identity field in SQL Server

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.1">
	<title>Choosing & Updating a Record</title>
<script language="VB" runat="server">
Dim intWdth, intID as integer
Dim strFirst, strLast, strTitle as string
Sub Page_Load(Source as Object, E as EventArgs)
	if not Page.IsPostBack then
		BindData
	End If
End Sub

Sub BindData()
	Dim strConn as string = "server=YourServer;uid=UID;pwd=PWD;database=YourDataBase"
	Dim sql as string = "Select id, fname, lname from TestInsert"
	Dim conn as New SQLConnection(strConn)
	Dim Cmd as New SQLCommand(sql, conn)
	Dim objDR as SQLDataReader
	conn.Open()
	objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
	list1.datasource=objDR
	list1.DataValueField="ID"
	list1.datatextfield="Lname"
	list1.databind
	list1.selectedindex=0
	conn.Close()

End Sub

Sub EditRecord(Source as Object, E as EventArgs)
Dim strConn as string = "server=YourServer;uid=UID;pwd=PWD;database=YourDataBase"
	Dim sql as string = "Select ID, Fname, Lname from TestInsert Where ID = "  & list1.selecteditem.value
	Dim conn as New SQLConnection(strConn)
	Dim objDR as SQLDataReader
	Dim Cmd as New SQLCommand(sql, conn)
	conn.Open()
	objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
	While objDR.Read()
	   intID=objDR("ID")
	   strFirst=objDR("Fname")
	   strLast=objDR("Lname")
	End While
	page.databind()
	label1.text=""
	label2.text=""

End Sub

Sub doUpdate(Source as Object, E as EventArgs)
	Dim strConn as string = "server=YourServer;uid=UID;pwd=PWD;database=Your_Db"
	Dim MySQL as string = "Update TestInsert Set Fname=@Fname, Lname=@Lname Where id=@ID"
	Dim Conn as New SQLConnection(strConn)
	Dim Cmd as New SQLCommand(MySQL, Conn)
	  cmd.Parameters.Add(New SQLParameter("@ID", lblID.text))
	  cmd.Parameters.Add(New SQLParameter("@Fname", frmFirstName.text))
	  cmd.Parameters.Add(New SQLParameter("@Lname", frmLastName.text))

	Conn.Open()
	cmd.ExecuteNonQuery
	label1.text = "It''s Done!"

	label1.text="Successfully updated -- - "
	BindData
	list1.SelectedIndex=List1.Items.IndexOf(List1.Items.FindByValue(lblID.text))

End Sub
</script>
</head>
<body>
<form Name="form1" runat="server">
<table border="1" width="100%">
	<tr>
		<td align="center"width="145" valign="Top"><b><i>Choose from List:</i></b><br>
<asp:ListBox id="list1" Width="125px" height="150px" runat="server" /><br>
<asp:button id="button1" Text="Edit Record" onclick="EditRecord" runat="server" />
		</td>

		<td align="Left" valign="Top">
<b>ID :</b> <asp:Label id="lblID" Text="<%# intID %>" runat="server" /><br>
<b>FirstName : </b> <asp:textbox id="frmFirstName" Text="<%# strFirst %>" runat="server" /><br>
<b>LastName : </b><asp:textbox id="frmLastName" runat="server" Text="<%# strLast %>" /><br>
<br>
<br>
<asp:button id="button2" Text="Update" onclick="doupdate" runat="server" />
<i><asp:Label ID="label1" forecolor="red" runat="server" /></i><br>
<i><asp:Label ID="label2" runat="server" /></i>
		</td>
	</tr>
</table>
</form>
</body>
</html>

DropDownList – DataField, ValueField (from DB)

This code sample uses the SQL Managed Provider, along with the Northwind Database (Employees table), to show how to populate a DropDownList with text as well as a value, and how to refer to them in order to retrieve the actual data.

As usual, just copy the code to a new file and change the connection info to match that of your system.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.1">
	<title>Untitled</title>
<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
	Dim strConn as string = "server=YourServer;uid=YourUID;pwd=YourPWD;database=NorthWind"
	Dim MySQL as string = "Select EmployeeID, LastName from Employees"
	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)
	ddl.DataSource = objDR
	ddl.DataBind()
end if
End Sub

Sub doit(Source as Object, E as EventArgs)
label1.text="<b><i>Selected Data:</i></b><br>Last Name = " & _
ddl.selecteditem.text & " (DataTextField)<br>" & _
"Employee ID = " & ddl.selectedItem.value & " (DataValuefield)"
End Sub
</script>
</head>
<body>
<Form id="form1" runat="server">
<asp:DropDownList id="ddl" DataValueField="EmployeeID" DataTextField="LastName" runat="server" />
<asp:Button id="button1" Text="Get Text & Value" onclick="doit" runat="server" />
</Form>
<asp:Label ID="label1"  runat="server" />
</body>
</html>

Display CSV File with DataGrid

This code sample shows how to read a .CSV file using the OleDb Managed Provider, and then display it, using a DataGrid. For this particular sample, after downloading the Lotto Texas Results in a CSV file, I just trimmed it a little for speed and ease of viewing. If no other .CSV file is available, you can download the full file here:
Download Lottery file
To make this work on your system, just adjust the path to match your needs on your system.

Also, this sample shows how to add Header Text when the .CSV file doesn’t have any headers. — Extra Thanks to DataGrid Girl for the extra help on the header definitions, since the CSV file comes without headers. To Do this, just create a DataBound Subroutine using DatagridItemEventArgs as an argument, then refer to it in the DataGrid properties:
OnItemDataBound=”DataBound”

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<script language="VB" runat="server">
	dim x as integer
Sub Page_Load(Source as Object, E as EventArgs)
	GetCSV()
End Sub

Sub GetCSV()
	Dim strConn As String
	strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
	"Data Source=c:\inetpub\wwwroot;Extended Properties=Text;"
	Dim Conn As New System.Data.OleDb.OleDbConnection(strConn)
	Conn.Open()

	Dim da As New System.Data.OleDb.OleDbDataAdapter("Select * from lotto.csv", Conn)
	Dim ds As New DataSet("lotto.csv")

	da.Fill(ds, "lotto.csv")
	Dim dt As DataTable
	dt = ds.Tables("lotto.csv")
	MyDataGrid.Datasource=ds.Tables("lotto.csv").DefaultView
	MyDataGrid.DataBind
End Sub

Sub DataBound (s as Object, e as DatagridItemEventArgs)
Select Case e.Item.ItemType
Case ListItemType.Header
	e.Item.Cells(0).Text="<b>Month</b>"
	e.Item.Cells(1).Text="<b>Day</b"
	e.Item.Cells(2).Text="<b>Year</b>"
	e.Item.Cells(3).Text="<b>First</b>"
	e.Item.Cells(4).Text="<b>Second</b>"
	e.Item.Cells(5).Text="<b>Third</b>"
	e.Item.Cells(6).Text="<b>Fourth</b>"
	e.Item.Cells(7).Text="<b>Fifth</b>"
	e.Item.Cells(8).Text="<b>Sixth</b>"
	For x=0 to 8
	e.item.cells(x).Font.Size= FontUnit.Point (14)
	next

Case ListItemType.Item, ListItemType.AlternatingItem

	For x=0 to 8
	e.item.Cells(x).HorizontalAlign=HorizontalAlign.Center
	e.item.cells(x).Font.Size= FontUnit.Point (11)
	next
End Select
End Sub
</script>

<div align="center">
<form runat="server" method="post">
<b><font Size="5" Color="#0000FF" Face="Arial">Lotto Texas Results</font></b>
<asp:Datagrid runat="server"
	Id="MyDataGrid"
	GridLines="Both"
	cellpadding="2"
	cellspacing="0"
	Headerstyle-BackColor="#8080C0"
	Headerstyle-Font-Name="Arial"
	Headerstyle-Font-Size="14"
	BackColor="#8080FF"
	Font-Name="Arial"
	Font-Size="12"
	AlternatingItemStyle-BackColor="#C0C0C0"
	AlternatingItemStyle-Font-Name="Arial"
	AlternatingItemStyle-Font-Size="11"
	BorderColor="Black"
	OnItemDataBound="DataBound">
</asp:DataGrid>
</form>
</div>

Getting a Directory's File List

Sometimes, it becomes necessary to actually list the files in a particular directory. To do this, we import the System.IO namespace. This code sample shows two different ways to display the directory. One way uses a Literal control to merely list them on the page, and the other uses a DropDownList control.

Additionally, we show ways to navigate to the files which are listed with each type of display. The DropDownList uses a simple redirector script, while the Literal control surrounds the filename with an HTML anchor tag.

To make this work on your system, just copy the code to your new file and change the path info to match that of your system.

<%@ Import Namespace="System.IO" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.1">
	<title>Untitled</title>
<script language="VB" runat="server">
Dim strFilePath as String
Sub Page_Load(Source as Object, E as EventArgs)
	Dim strEntries() As String
	Dim f, sFiles As String
	strFilePath = Server.MapPath("/files/")
	strEntries = Directory.GetFiles(strFilePath)

	For Each f In strEntries
		Dim Filename as String=path.GetFilename(f)
		if not Page.IsPostBack then
			ddl.items.add(Filename)
		end if
		strFilePath=strFilePath.Replace("\", "/")
		strFilePath=strFilePath.Replace("c:/Inetpub/wwwroot", "")

		sFiles=sFiles & "<a href=" & chr(34) & strFilePath & Filename & chr(34) & ">" & Filename & "</a><br>"
		lt.text=sFiles
	Next
End Sub

Sub doit(Source as Object, E as EventArgs)
	Dim sRedir as string
	strFilePath = Server.MapPath("/files/")

	sRedir = strFilePath & ddl.selectedItem.text
	sRedir=sRedir.Replace("\", "/")
	sRedir=sRedir.Replace("c:/Inetpub/wwwroot", "")
	response.Redirect(sRedir)
End Sub
</script>

</head>
<body>
<Form id="form1" runat="server">
<asp:DropDownList id="ddl" runat="server" />
<asp:Button id="button1" Text="Do It" onclick="doit" runat="server" /><br>
<asp:Literal ID="lt" runat="server"></asp:literal>
</Form>
<asp:Label ID="label1"  runat="server" />
</body>
</html>

Nested DataLists

Sometimes, we need to nest data – say for instance – List the Categories, and under each Category, list the Products for that particular Category.

This sample uses the SQL Managed Provider to show exactly that, using the Categories and Products tables from the NorthWind Database.

As usual, just copy this code directly into a new page, change the database/connection information to match your system, and run it from your own computer. There is an updated portion here, explaining how to format the price for each of the products in the table, also.

You can read a Tutorial about this code here.

See this code in C# (provided by Mike Houston)

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.1">
	<title>Nested DataLists</title>
<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
	Dim strConn as string = "server=YourServer;uid=UID;pwd=PWD;database=Northwind"
	Dim MySQL as string = "Select CategoryID, CategoryName from Categories"
	Dim MyConn as New SQLConnection(strConn)
	Dim ds as DataSet=New DataSet()

	Dim Cmd as New SQLDataAdapter(MySQL,MyConn)
	Cmd.Fill(ds,"Categories")

        	Dim cmd2 As SqlDataAdapter = New SqlDataAdapter("select * from Products", MyConn)
        	cmd2.Fill(ds, "Products")

        	ds.Relations.Add("myrelation", ds.Tables("Categories").Columns("CategoryID"), ds.Tables("Products").Columns("CategoryID"))

	dlCategories.Datasource=ds.Tables("Categories").DefaultView
	DataBind()
End Sub

Function doFormat(sItem as Decimal)
	Dim s as String
	s=String.Format("{0:c}", sItem)
	doFormat=s
End function

</script>
</head>
<body>
<asp:DataList runat="server"
	Id="dlCategories"
	GridLines="Both"
	Bordercolor="black"
	cellpadding="3"
	cellspacing="0"
	Headerstyle-BackColor="#DDDDDD"
	Headerstyle-Forecolor="#777777"
	Headerstyle-Font-Name="Arial"
	Headerstyle-Font-Size="14"
	Headerstyle-Font-Bold="true"
	Font-Name="Arial"
	Font-Bold="true"
	Font-Italic="true"
	Font-Size="11"
	ForeColor="Red"
	RepeatColumns="1">
	<HeaderTemplate>
		Categories & Products
	</HeaderTemplate>
	<ItemTemplate><%# Container.DataItem("CategoryName")%>
		 <br>
			<asp:DataList runat="server"
				Id="ChildDataList"
				GridLines="None"
				Bordercolor="black"
				cellpadding="3"
				cellspacing="0"
				Headerstyle-BackColor="#8080C0"
				Headerstyle-Font-Name="Arial"
				Headerstyle-Font-Size="8"
				Font-Name="Arial"
				Font-Size="8"
				datasource='<%# Container.DataItem.Row.GetChildRows("myrelation") %>'
				RepeatColumns="3">
				<ItemTemplate>
					&nbsp; &nbsp; <%# Container.DataItem("ProductName") %>
					 - <%# doFormat(Container.DataItem("UnitPrice")) %>

				</ItemTemplate>
			</ASP:DataList>
	</ItemTemplate>
</ASP:DataList>
</body>
</html>

Populate DropDownList with Stored Procedure

This sample uses the SQL Managed Provider and the Northwind Database to do the following:
Populate a RadioButtonList with the Category Names (using the CategoryID as the value field)

Then, based on the selection from the RadioButtonList, a DropDownList is populated, using a Stored Procedure, with all the Product Names that fall in the selected Category.

Just copy the code into new page on your site and change the connection information.

Stored Procedure:
Create Procedure [GetProductsByCategory]
@CatID int
as
Select ProductName
from Products where CategoryID=@CatID
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.1">
	<title>Populating a DropDownList from a RadioButtonList</title>
<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
	Dim strConn as string = "server=YourServer;uid=YourUID;pwd=YourPWD;database=Northwind"
	Dim MySQL as string = "Select CategoryID, CategoryName from NWCategories"
	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)
	rb1.DataSource = objDR
	rb1.DataBind()
end if
End Sub
Sub popddl(Source as Object, E as EventArgs)
	Dim strConn as string = "server=YourServer;uid=YourUID;pwd=YourPWD;database=Northwind"
	Dim MySQL as string = "GetProductsByCategory"   ' Substitute Stored Proc Name for SQL string
	Dim MyConn as New SQLConnection(strConn)
	Dim objDR as SQLDataReader
	Dim Cmd as New SQLCommand(MySQL, MyConn)
        cmd.CommandType=CommandType.StoredProcedure    ' Tells application that it's using a Stored Procedure
	cmd.parameters.add(New SQLParameter("@CatID", rb1.selecteditem.value))
	MyConn.Open()
	objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
	ddl.DataSource = objDR
	ddl.DataBind()
	ddl.visible="true"
	lblProduct.text="Products in " & rb1.selecteditem.text & " Category"
	label1.text= ("Selected Value = " & rb1.selecteditem.value )
End Sub
</script>

</head>
<body>
<Form id="form1" runat="server">

<table border="0">
        <tr>
		<td align="Left" valign="Top"><b><i>Categories:</i></b><br>
		<asp:RadioButtonList id="rb1" datatextfield="CategoryName" datavaluefield="CategoryID" runat="server">
		</asp:RadioButtonList> <asp:Button id="button1" Text="Get Products" onclick="popddl" runat="server" />
		</td>

		<td align="Left" valign="Top"><b><i><asp:Label ID="lblProduct"  runat="server" /></i></b><br>
		<asp:DropDownList id="ddl" datatextfield="Productname" visible="false" runat="server" /></td>
	</tr>
</table>

</Form>
<asp:Label ID="label1"  runat="server" />
</body>

Populating a DropDownList from a RadioButtonList

This sample uses the SQL Managed Provider and the Northwind Database to do the following:
Populate a RadioButtonList with the Category Names (using the CategoryID as the value field)

Then, based on the selection from the RadioButtonList, a DropDownList is populated with all the Product Names that fall in the selected Category.

Just copy the code into new page on your site and change the connection information.

Thanks to Joseph Janick for this next suggestion – he wanted to know how to make it work without the ‘Get Products’ button. It’s much simpler than most would think. Since the population of the DropDownList is being done in the ‘popddl’ Subroutine, after removing the button from the form, only two sections need to be added. In the RadioButtonList control itself, in the HTML, add these two items:
onselectedindexchanged=”popdll”
and
autopostback=”true”

The AutoPostback Property, being set to ‘True’, takes the place of the button. When you click on the RadioButtonList item, this tells it to automatically postback and run the sub or function designated in the onselectedindexchanged method.

It couldn’t get any simpler than that!

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.1">
	<title>Populating a DropDownList from a RadioButtonList</title>
<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
	Dim strConn as string = "server=YourServer;uid=YourUID;pwd=YourPWD;database=Northwind"
	Dim MySQL as string = "Select CategoryID, CategoryName from NWCategories"
	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)
	rb1.DataSource = objDR
	rb1.DataBind()
end if
End Sub
Sub popddl(Source as Object, E as EventArgs)
	Dim strConn as string = "server=YourServer;uid=YourUID;pwd=YourPWD;database=Northwind"
	Dim MySQL as string = "Select ProductName from NWProducts Where CategoryID = @CatID"
	Dim MyConn as New SQLConnection(strConn)
	Dim objDR as SQLDataReader
	Dim Cmd as New SQLCommand(MySQL, MyConn)
	cmd.parameters.add(New SQLParameter("@CatID", rb1.selecteditem.value))
	MyConn.Open()
	objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
	ddl.DataSource = objDR
	ddl.DataBind()
	ddl.visible="true"
	lblProduct.text="Products in " & rb1.selecteditem.text & " Category"
	label1.text= ("Selected Value = " & rb1.selecteditem.value )
End Sub
</script>

</head>
<body>
<Form id="form1" runat="server">

<table border="0">	<tr>
		<td align="Left" valign="Top"><b><i>Categories:</i></b><br>
		<asp:RadioButtonList id="rb1" datatextfield="CategoryName" datavaluefield="CategoryID" runat="server">
		</asp:RadioButtonList> <asp:Button id="button1" Text="Get Products" onclick="popddl" runat="server" />
		</td>

		<td align="Left" valign="Top"><b><i><asp:Label ID="lblProduct"  runat="server" /></i></b><br>
		<asp:DropDownList id="ddl" datatextfield="Productname" visible="false" runat="server" /></td>
	</tr>
</table>

</Form>
<asp:Label ID="label1"  runat="server" />
</body>

Filling an ArrayList from a Database Table

Some ASP.Net server controls do not have a sort property, among other things that might be needed. Therefore, it becomes necessary to use an ArrayList, or the like, so that you can work with the ArrayList itself and then bind it to the server control, like a DropDownList, which is used in this sample.

This is a very simple example of reading through the records of a table, using SQL Server and the Northwind Database (Categories table), adding the items to the ArrayList, and then, binding the ArrayList to the DropDownList

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.1">
	<title>Untitled</title>
<script language="VB" runat="server">
Dim MyArrayList as ArrayList
Dim sItem as String
Sub Page_Load(Source as Object, E as EventArgs)
MyArrayList=New Arraylist
if not Page.IsPostBack then
Dim strConn as string = "server=YourServer;uid=UID;pwd=PWD;database=NorthWind"
	Dim MySQL as string = "Select CategoryName from Categories"
	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)
	While objDR.Read()
		MyArrayList.add(objDR("CategoryName"))
	End While
end if
ddl1.datasource=MyArrayList
ddl1.databind
End Sub
</script>
</head>
<body>

<Form id="form1" runat="server">
<asp:DropDownList id="ddl1" runat="server" />
</Form>
</body>
</html>

Getting Record Count with a DataReader

This code sample uses the Northwind.mdb database (OleDb) to show how to get a recordcount returned, using a DataReader. There is no where clause with this sample, since it allows the end user to select the table for the count, but works equally as well with a where clause.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDB" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.1">
	<title>Untitled</title>
<script language="VB" runat="server">
Dim intNum as Integer
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
	ddl.items.add("Products")
	ddl.items.add ("Customers")
	ddl.items.add ("Categories")
	ddl.items.add("Employees")
end if
End Sub
Sub doCount(Source as Object, E as EventArgs)

Dim MySQL as string = "Select * from " & ddl.selecteditem.text

Dim strConn as string = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & server.mappath("\data\northwind.MDB") & ";"
Dim MyConn as New OleDBConnection(strConn)
Dim objDR as OleDBDataReader
Dim Cmd as New OLEDBCommand(MySQL, MyConn)
MyConn.Open()
objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
intNum=0
While objDR.Read()
  intNum = intNum+1
End While
label1.text= ("<b><i><font Color=""#8000FF"">Number of Records in " & ddl.selecteditem.text & "Table</font></i> : </b>" & intNum)
End Sub
</script>
</head>
<body>
<Form id="PutIDNameHere" runat="server">
<asp:DropDownList id="ddl" runat="server" /><asp:Button id="button1" Text="Get Count" onclick="docount" runat="server" />
</Form>
<asp:Label ID="label1"  runat="server" />
</body>
</html>