Hierarchical Master/Detail

There are quite a few different concepts shown in this sample. Here’s the meaning of the title. This sample shows how to choose from a list of categories, therefore producing a list of products inside that category. Then, from the list of products, you can get the details of that particular product.

Once again, this sample uses the Northwind database, but it uses both the Categories and the Products tables. It’s a SQL Server example, but as always, you can take the SQL code and run it through the Database Code Conversion Tool to get it converted to an OleDb example.

Among the many concepts this sample shows are:

  • How to select and refer to an item in a DataGrid
  • Use of the DataGrid’s ItemCommand and DataGridCommandEventArgs
  • DataLists with Header and Item Templates
  • DataGrids with ItemTemplates, using a LinkButton
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<script language="VB" runat="server">
Dim sCategory as String
Dim sProduct as String
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 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)
	dg.DataSource = objDR
	dg.DataBind()
	MyConn.Close
end if
End Sub

Sub dg_ItemCommand(sender As Object, e As DataGridCommandEventArgs)
Dim strConn as string = "server=YourServer;uid=YourUID;pwd=YourPwd;database=Northwind"
if e.commandname="doCats" then
	sCategory=CType(e.Item.FindControl("lb1"), LinkButton).Text
	pnl1.visible=false
	pnl2.visible=true
	Dim intID as integer = dg.DataKeys(e.Item.ItemIndex)
	Dim MySQL as string = "Select Products.ProductID, Products.ProductName from " & _
	"Products where CategoryID=" & dg.DataKeys(e.Item.ItemIndex) & " Order by Products.ProductID"
	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)
	dg2.DataSource = objDR
	dg2.DataBind()
	MyConn.Close
elseif e.commandname="doProds" then
	sProduct=CType(e.Item.FindControl("lb2"), LinkButton).Text
	Dim intID as integer = dg2.DataKeys(e.Item.ItemIndex)
	pnl1.visible=false
	pnl2.visible=true
	Dim MySQL as string = "Select * from Products where ProductID=" & 	dg2.DataKeys(e.Item.ItemIndex)
	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)
	dl.DataSource = objDR
	dl.DataBind()
	MyConn.Close
End If
End Sub
</script>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.0">
	<title>Hierarchical Master/Detail<</TITLE>
	<Link REL=STYLESHEET HREF="/basicArial.css" TYPE="text/css">

</head>
<body><form id="form1" runat="server">
<asp:panel ID="pnl1"  runat="server">

<div align="center">
<asp:Datagrid runat="server"
	Id="dg"
	GridLines="None"
	cellpadding="0"
	cellspacing="0"
	Headerstyle-BackColor="#FFFFFF"
	Headerstyle-Forecolor="#FFFFFF"
	Headerstyle-Font-Name="Arial"
	Headerstyle-Font-Size="12"
	 HeaderStyle-Font-Bold="True"
	BackColor="#FFFFFF"
	Font-Name="Arial"
	Font-Size="10"
	 Width="100%"
	 DataKeyField="CategoryID"
	 AutoGenerateColumns="False"
	 OnItemCommand="dg_ItemCommand">
	<columns>
		<asp:TemplateColumn>
			<HeaderTemplate>
				<b><i><font Size="4" Color="#0000FF">Categories</font></i></b>
			</HeaderTemplate>
			<ItemTemplate>
				<asp:LinkButton id="lb1" HeaderText=''<%# Container.DataItem("CategoryName") %>''
				Text=''<%# Container.DataItem("CategoryName") %>''
				CommandName="doCats" runat="server" />
			</ItemTemplate>
		</asp:TemplateColumn>
	</columns>
</asp:DataGrid>
</div>
</asp:panel>

<asp:panel ID="pnl2" Visible="false" runat="server">

<div align="center"><table width="100%">	<tr>
		<td align="Left" valign="Top">
		<asp:DataGrid runat="server"
		Id="dg2"
		GridLines="None"
		cellpadding="0"
		cellspacing="0"
		Headerstyle-BackColor="#FFFFFF"
		Headerstyle-Forecolor="#0F0F0F"
		Headerstyle-Font-Name="Arial"
		Headerstyle-Font-Size="12"
		 HeaderStyle-Font-Bold="True"
		BackColor="#FFFFFF"
		Font-Name="Arial"
		Font-Size="10"
		 BorderColor="Black"
		 RepeatColumns="4"
		 RepeatDirection="Horizontal"
		 AutoGenerateColumns="False"
		 OnItemCommand="dg_ItemCommand"
		 DataKeyField="ProductID">
		<columns>
			<asp:TemplateColumn>
				<HeaderTemplate>
					<b><font Size="4" Color="#0000FF"><i>Products (Category -
						<%# sCategory%>)</i></font></b>
				</HeaderTemplate>
				<ItemTemplate>
					<asp:LinkButton id="lb2" Text=''<%# Container.DataItem("ProductName") %>''
                                       CommandName="doProds" runat="server" />
				</ItemTemplate>
			</asp:TemplateColumn>
		</columns>
		</asp:DataGrid>
		</td>
		<td align="Left" valign="Top">
		<asp:DataList runat="server"
			Id="dl"
			GridLines="None"
			cellpadding="0"
			cellspacing="0"
			RepeatColumns="1"
			RepeatDirection="Horizontal"
			Headerstyle-BackColor="#FFFFFF"
			Headerstyle-Forecolor="#0F0F0F"
			Headerstyle-Font-Name="Arial"
			Headerstyle-Font-Size="8"
			BackColor="#C6C3FF"
			Font-Name="Arial"
			Font-Size="10">
			<HeaderTemplate>
				<b><font Size="4" Color="#0000FF"><i>Product Name  - <%# sProduct%></i></font></b>
			</HeaderTemplate>
			<ItemTemplate>
				<b>CategoryID: </b><%# Container.DataItem("CategoryID") %><br>
				<b>Quantity Per Unit: </b><%# Container.DataItem("QuantityPerUnit") %><br>
				<b>Unit Price: </b><%# String.Format("{0:c}", Container.DataItem("UnitPrice")) %><br>
				<b>Units In Stock: </b><%# Container.DataItem("UnitsInStock") %><br>
				<b>Reorder Level: </b><%# Container.DataItem("ReorderLevel") %><br>
			</ItemTemplate>
		</ASP:DataList>

		</td>
	</tr>
</table></div>
<div align="center"><hr>
<A HREF="/dw/choose.aspx">Choose a Category</A></div>
</asp:panel>
</form>
</body>
</html>

Editing an MS Access Table using a DataGrid

This is an MS Access version of a previously posted SQL Server example, showing how to Edit/Update with a DataGrid. It uses the Employees table of the Northwind DataBase.

Several things are necessary for creating these features in the DataGrid. First, you just add an ‘Edit/Update/Cancel’ button column to the grid. Second, for each of those options (Edit/Update/Cancel), you need to create a subroutine that takes care of that particular task. In this case, they are MyDataGrid_EditCommand, MyDataGrid_Cancel, and MyDataGrid_UpdateCommand. The first two are fairly self-explanatory, but the last one, the UpdateCommand, has the real ‘meat’ of this code sample. It provides the actual code for updating the database.

Also, another neat thing that you will probably notice, is it shows how to put an image into the EditText area of the EditColumn. To use this image, just right click on the Pencil and save the image to your computer.

Note – you may need to refresh the page in order to see updates.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.0b1">
	<title>Editing an MS Access Table using a DataGrid</title>
<script language="VB" runat="server">
Sub MyDataGrid_EditCommand(s As Object, e As DataGridCommandEventArgs )
	MyDataGrid.EditItemIndex = e.Item.ItemIndex
	BindData
End Sub

Sub MyDataGrid_Cancel(Source As Object,   E As DataGridCommandEventArgs)
	MyDataGrid.EditItemIndex = -1
	BindData()
End Sub

Sub MyDataGrid_UpdateCommand(s As Object, e As DataGridCommandEventArgs )
	Dim conn As OleDbConnection
	Dim MyCommand As OleDbCommand
	Dim strConn as string = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
	server.mappath("\Data\Nwind.mdb") & ";"
	Dim txtFirstName As textbox = E.Item.cells(2).Controls(0)
	Dim txtLastName As textbox = E.Item.cells(3).Controls(0)
	Dim txtTitle As textbox = E.Item.cells(4).Controls(0)
	Dim strUpdateStmt As String
        strUpdateStmt =" UPDATE Employees SET" & _
        " FirstName =@Fname, LastName =@Lname, Title = @Title " & _
        " WHERE EmployeeID = @EmpID"
	conn = New OleDbConnection(strConn)
	MyCommand = New OleDbCommand(strUpdateStmt, conn)
	MyCommand.Parameters.Add(New OleDbParameter("@Fname", txtFirstName.text))
	MyCommand.Parameters.Add(New OleDbParameter("@Lname", txtLastName.text))
	MyCommand.Parameters.Add(New OleDbParameter("@Title", txtTitle.text))
	MyCommand.Parameters.Add(New OleDbParameter("@EmpID", e.Item.Cells(1).Text ))
	conn.Open()
	MyCommand.ExecuteNonQuery()
	MyDataGrid.EditItemIndex = -1
        conn.close
	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 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
	server.mappath("\Data\Nwind.mdb") & ";"
	Dim sql as string = "Select EmployeeID, FirstName, LastName, Title from Employees"
	Dim conn as New OleDbConnection(strConn)
	Dim objDR as OleDbDataReader
	Dim Cmd as New OleDbCommand(sql, conn)

	conn.Open()
	objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
	MyDataGrid.DataSource = objDR
	MyDataGrid.DataBind()
        conn.close
End Sub
</script>
</head>
<body><div align="center">
<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-Size="12"
        	Headerstyle-Font-Bold="True"
	BackColor="#8080FF"
	Font-Name="Arial"
	Font-Size="11"
	BorderColor="Black"
	AutogenerateColumns="False"
	OnEditcommand="MyDataGrid_EditCommand"
	OnCancelcommand="MyDataGrid_Cancel"
	OnUpdateCommand="MyDataGrid_UpdateCommand">
	<Columns>
		<asp:EditCommandColumn
			ButtonType="LinkButton"
			UpdateText="Update"
			CancelText="Cancel"
			EditText="<IMG SRC=/images/Edit.gif Border=0 Width=12 Height=12>"
                                                ItemStyle-HorizontalAlign="Center"
		                HeaderText="Edit">
		</asp:EditCommandColumn>
		<asp:BoundColumn
			DataField="EmployeeID"
			HeaderText="EmployeeID"
			ReadOnly="True">
		</asp:BoundColumn>
		<asp:BoundColumn
			DataField="FirstName"
			HeaderText="FirstName">
		</asp:BoundColumn>
		<asp:BoundColumn
			DataField="LastName"
			HeaderText="LastName">
		</asp:BoundColumn>
		<asp:BoundColumn
			DataField="Title"
			HeaderText="Title">
		</asp:BoundColumn>
	</Columns>
</asp:DataGrid>
</form>
</div>
</body>
</html>

CheckBoxes, DataGrids & Selection

This sample uses the Employees table of the Northwind database, along with the SQL Server managed provider to show a couple of different ways of how to get the values of selected items within a DataGrid, using checkboxes.

Also, notice that, in creating the string for the label, we used a couple of the new .Net string properties, so that, once the string was built, the way to remove the final comma and space combination was like this:
sList=sList.Substring(0,sList.length-2)

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.0b1">
	<title>Checkboxes in a DataGrid - Check All</title>
<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
	BindGrid
end if
End Sub

Sub BindGrid()
	Dim strConn as string = "server=YourServer;uid=YourUID;pwd=YourPWD;database=NorthWind"
	Dim MySQL as string = "Select FirstName, LastName, Title, HireDate 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)
	MyDataGrid.DataSource = objDR
	MyDataGrid.DataBind()
End Sub

Sub GetItems(Source as Object, E as EventArgs)
	Dim GridItem As DataGridItem
	Dim chkBox as System.Web.UI.WebControls.CheckBox
	Dim sName, sList, sTitle as String
                For Each GridItem In MyDataGrid.Items
		chkBox = GridItem.FindControl("myCheckbox")
		If chkBox.Checked Then
		sName=CType(GridItem.FindControl("lblFirst"), Label).Text & " " & _
		CType(GridItem.FindControl("lblLast"), Label).Text
		sTitle=GridItem.Cells(3).Text
		sList +=  sName & "/" & sTitle & ", "
		End If
        Next
	sList=sList.Substring(0,sList.length-2)
	label1.text="<b>You Chose :</b> <br>" & sList
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-Size="8"
	BackColor="#8080FF"
	Font-Name="Arial"
	Font-Size="8"
	BorderColor="Black"
	AutogenerateColumns="False">
	<Columns>
		<asp:TemplateColumn>
			<ItemTemplate>
				<asp:CheckBox ID="myCheckbox" Runat="server">
				</asp:CheckBox>
			</ItemTemplate>
		</asp:TemplateColumn>
			<asp:TemplateColumn HeaderText="Last Name">
				<ItemTemplate>
					<asp:Label ID="lblFirst" runat="server"
					Text=''<%# DataBinder.Eval(Container.DataItem, "FirstName") %>''/>
				</ItemTemplate>
			</asp:TemplateColumn>
			<asp:TemplateColumn HeaderText="Last Name">
				<ItemTemplate>
					<asp:Label ID="lblLast" runat="server"
					Text=''<%# DataBinder.Eval(Container.DataItem, "LastName") %>''/>
				</ItemTemplate>
			</asp:TemplateColumn>
		<asp:BoundColumn DataField="Title" HeaderText="Title">
		</asp:BoundColumn>
		<asp:BoundColumn DataField="HireDate" HeaderText="HireDate">
		</asp:BoundColumn>
	</Columns>
</asp:DataGrid>
<asp:Button id="btnGet" Text="Get Checked Items" onclick="GetItems" runat="server" />
</form>
<asp:Label ID="label1" Runat="Server">
</asp:Label>
</body>
</html>

Ad Hoc Sorting with a DataGrid

Yes, the ASP.Net DataGrid has built in Sorting capabilities. However, this code sample shows an alternative way to the built-in sorting routine, using DropDownLists. This example could easily be expanded to multiple sort fields.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<script language="VB" runat="server">
Dim sOrderby as String
Dim sDirection as String
Dim MySQL as String
Sub BindData(Source as Object, E as EventArgs)
sOrderby=ddl.selectedItem.text
sDirection=ddlDir.selectedItem.value
	Dim strConn as string = "server=YourServer;uid=YourUID;pwd=YourPWD;database=Northwind"
if sOrderby="" and sDirection="" then
	MySQL = "Select FirstName, LastName, Title, Address, City, ReportsTo from Employees"
else
	MySQL = "Select FirstName, LastName, Title, Address, City, ReportsTo from Employees " & _
"order by " & sOrderBy & " " & sDirection
end if
	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>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.0">
	<title>Ad Hoc Sorting with a DataGrid</title>
</head>
<body>
<Form id="form1" runat="server">
<table>
	<tr>
		<td align="Left" valign="Top"><b><i>View Employee Data</i></b></td>
		<td align="right" valign="Top">
		Order by: <asp:dropdownlist id="ddl" runat="server">
			<asp:listitem value="FirstName">FirstName</asp:listitem>
			<asp:listitem value="LastName">LastName</asp:listitem>
			<asp:listitem value="Title">Title</asp:listitem>
			<asp:listitem value="Address">Address</asp:listitem>
			<asp:listitem value="City">City</asp:listitem>
			<asp:listitem value="ReportsTo">ReportsTo</asp:listitem>
		</asp:dropdownlist>
		Direction: <asp:dropdownlist id="ddlDir" runat="server">
			<asp:listitem value="asc">Ascending</asp:listitem>
			<asp:listitem value="desc">Descending</asp:listitem>
		</asp:dropdownlist>
		</td>
	</tr>
	<tr>
		<td align="Left" valign="Top" Colspan="2">
<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="#EFEFEF"
	AlternatingItemStyle-Font-Name="Arial"
	AlternatingItemStyle-Font-Size="10"
	BorderColor="Black">
</asp:DataGrid><br>
<asp:Button id="btn1" Text="View Records" onclick="BindData" runat="server" />
</td>
	</tr>
</table>
</form>

</body>
</html>

Master – Detail Page

This code sample uses the SQL Managed Provider to create a Master/Detail page. The ‘Details’ link in the initial ‘Master’ DataGrid utilizes a HyperlinkColumn. In this case, you will create only one page, but you can just as easily create it so that the Details show up in another page.

All you’d need to do is to eliminate the “doShowDetails” subroutine in the original page, and put the code from that routine into the Page_Load of the second page. Remember, along with changing the connection string for your particular needs, you’ll need to change the DataNavigateURLFormatString of the HyperLinkColumn to reflect whatever your pagename is.

Doing it in two pages is a little trickier – -
outside the page load (in the script tags, if you’re doing inline coding) –
dim a variable for each of the querystring items you’re retrieving
(like Dim iEmpID as Integer)
- – then, in the page_load event – do something like:
iEmpID=request.Querystring(“id”)
Then, use the variable, iEmpID in the where clause of the SQL statement

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.0">
	<title>Untitled</title>
<script language="VB" runat="server">
Dim sDetails as String
Dim intID as String
Sub Page_Load(Source as Object, E as EventArgs)

if not Page.IsPostBack then
	Dim strConn as string = "server=(local);uid=YourUID;pwd=YourPWD;database=Northwind"
	Dim MySQL as string = "Select Employees.EmployeeID, Employees.FirstName, " & _
	"Employees.LastName from Employees"
	Dim conn as New SQLConnection(strConn)
	Dim ds as DataSet=New DataSet()
	Dim Cmd as New SQLDataAdapter(MySQL,conn)
	Cmd.Fill(ds,"Employees")
	MyDataGrid.Datasource=ds.Tables("Employees").DefaultView
	MyDataGrid.DataBind()
end if
sDetails=request.QueryString ("action")
intID=Request.QueryString("id")

if sDetails="details" then
pnl1.visible="true"
doShowDetails
end if

End Sub
Sub doShowDetails()
	Dim strConn as string = "server=(local);uid=YourUID;pwd=YourPWD;database=Northwind"
	Dim MySQL as string = "Select *  from Employees where EmployeeID=" & intID
	Dim conn as New SQLConnection(strConn)
	Dim ds as DataSet=New DataSet()
	Dim Cmd as New SQLDataAdapter(MySQL,conn)
	Cmd.Fill(ds,"Employees")
	MyDataList.Datasource=ds.Tables("Employees").DefaultView
	MyDataList.DataBind()
End Sub
</script>
</head>
<body>
<form runat="server" method="post">
<table>	<tr>
		<td align="Left" valign="Top"><asp:Datagrid runat="server"
	Id="MyDataGrid"
	GridLines="Both"
	cellpadding="0"
	cellspacing="0"
	Headerstyle-BackColor="#0000FF"
	Headerstyle-Forecolor="#FFFFFF"
	Headerstyle-Font-Name="Arial"
	Headerstyle-Font-Bold="True"
	Headerstyle-Font-Size="12"
	BackColor="#8080C0"
	Font-Name="Arial"
	Font-Size="10"
	AlternatingItemStyle-BackColor="#C0C0C0"
	AlternatingItemStyle-Font-Name="Arial"
	AlternatingItemStyle-Font-Size="10"
	BorderColor="Black"
	AutogenerateColumns="False">
	<Columns>
		<asp:HyperLinkColumn HeaderText="Details"
			DataNavigateURLField="EmployeeID"
			DataNavigateURLFormatString="YourPageName.aspx?id={0}&action=details"
			Text="Details" />
		<asp:BoundColumn
			DataField="LastName"
			HeaderText="LastName">
		</asp:BoundColumn>
		<asp:BoundColumn
			DataField="FirstName"
			HeaderText="FirstName">
		</asp:BoundColumn>
	</Columns>
</asp:DataGrid>
</td>
		<td align="Left" valign="Top">
		<asp:panel ID="pnl1"  Visible="False"  runat="server">
			<asp:DataList runat="server"
				Id="MyDataList"
				GridLines="None"
				cellpadding="2"
				cellspacing="2"
				Headerstyle-BackColor="#FFFFFF"
				Headerstyle-Forecolor="#FFFFFF"
				Headerstyle-Font-Name="Arial"
				Headerstyle-Font-Size="10"
				BackColor="#FFFFFF"
				Font-Name="Arial"
				Font-Size="10">
				<ItemTemplate>
			<font Size="4"><%# Container.DataItem("FirstName") %>
			<%# Container.DataItem("LastName") %>/<%# Container.DataItem("Title") %></font><br>
			<b>BirthDate:</b> <%# Container.DataItem("BirthDate") %><br>
			<b>Hire Date: </b><%# Container.DataItem("HireDate") %><br>
			<b>Address:</b> <br>
			<%# Container.DataItem("Address") %><br>
			<%# Container.DataItem("City") %>, <%# Container.DataItem("Region") %>
			<%# Container.DataItem("PostalCode") %><br>
			<b>Phone:</b> <%# Container.DataItem("HomePhone") %>
				</ItemTemplate>
			</ASP:DataList>
		</asp:panel>
		</td>
	</tr>
</table>
</form>
</body>
</html>

Getting CheckBoxList Selected Items

This sample uses the Northwind Database (OleDb Managed Provider) to populate a CheckBoxList. Then, the code goes on to show how to get the list of selected items.

Also, since we’re displaying the items, separated by a comma, we use a couple of string functions to display it. When we say ‘Stuff = Stuff & Item.Text & “, “‘, naturally, when we get to the last item selected, there is also a comma at the end of it. To ‘chop’ it down, we use the length function to help us do this.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDB" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.5">
<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)

if not Page.IsPostBack then
	Dim strConn as string = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & server.mappath("\northwind.mdb") & ";"
	Dim MySQL as string = "Select CategoryID, CategoryName from Categories"
	Dim conn as New OleDBConnection(strConn)
	Dim objDR as OleDBDataReader
	Dim Cmd as New OLEDBCommand(MySQL, conn)
	conn.Open()
	objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
	cbl1.DataSource = objDR
	cbl1.DataTextField="CategoryName"
	cbl1.DataValueField="CategoryID"
	cbl1.DataBind()
end if
End Sub

Sub doit(Source as Object, E as EventArgs)
Dim Stuff as String
   Dim Item As ListItem
        For Each Item In cbl1.Items
            If Item.Selected Then
                Stuff = Stuff & Item.Text & ", "
            End If
        Next
Stuff=Stuff.Substring(0, (stuff.length-2))
label1.text=" <b>Selected Items Were: </b><br> " & stuff
End Sub
</script>
	<title>Getting CheckBoxList Selected Items</title>
</head>
<body>
<Form id="Form1" runat="server">
<asp:CheckBoxList id="cbl1" runat="server" /><asp:Button id="button1" Text="Get Items" onclick="doit" runat="server" />
<br>
<asp:Label ID="label1"  runat="server" />
</Form>
</body>

Confirmation Before Form Submission

Sometimes, we need to add a Javascript confirmation attribute to a button’s click event. When the button is clicked, this will give them an extra pop-up box that says something like, “Are you SURE you want to submit this form?”.

This sample shows how to do this, inside the Page_Load event, showing how to add the ‘onclick’ event as an attribute, to the button which submits the form.

<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.2">
	<title>Confirmation Before Form Submission</title>
<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
Button1.Attributes("OnClick") = "return confirm(''Would you like to submit this form?'');"
End Sub

Sub doit(Source as Object, E as EventArgs)
	label1.text="The Name you entered is " & txtFirst.text & " " & txtLast.text
End Sub
</script>
</head>
<body>
<Form id="form1" runat="server">
First Name: <asp:TextBox id="txtFirst" runat="server" /><br>
Last Name: <asp:TextBox id="txtLast" runat="server" />
<asp:Button id="Button1" Text="Submit" onclick="doit" runat="server" />
</Form>
<asp:Label ID="label1"  runat="server" />
</body>
</html>

Handling Database Nulls with a DataReader

In this code sample, I use the OleDb Managed Provider (with the MS Access Biblio Database) to show how to handle Database Nulls with a Datareader. This uses a ‘helper function’ in order to handle null values at display time.

As it turns out, there weren’t many actual ‘Year Born’ dates entered into the database, so I had to add in a few just to show a varied display.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDB" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.2">
	<title>Handling Database Nulls with a DataReader</title>
	<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
	Dim strConn as string = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" _
	& server.mappath(".\BIBLIO.MDB") & ";"
	Dim MySQL as string = "Select author, [Year Born] from Authors"
	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)
	MyDataList.DataSource = objDR
	MyDataList.DataBind()
End Sub

Function fixBirthDate(sItem) as String
if sItem is System.DBNull.Value Then
	fixBirthDate="<i><font Color=''#FF0000''>No Date Specified</font></i>"
else
	fixBirthDate="<b>" & sItem & "</b>"
End If
End function

</script>
</head>
<body>

<asp:DataList runat="server"
	Id="MyDataList"
	GridLines="Both"
	cellpadding="2"
	cellspacing="2"
	Headerstyle-Font-Name="Arial"
	Headerstyle-Font-Size="8"
	Font-Name="Arial"
	Font-Bold="false"
	RepeatDirection="Horizontal"
	RepeatColumns="4"
	Font-Size="8">
	<ItemTemplate>
		<%# Container.DataItem("Author")%> -
		<%# fixBirthDate(Container.DataItem("YearBorn"))%>
	</ItemTemplate>
</ASP:DataList>

</body>
</html>

Checking User ID in Database

This sample shows how to check user input against data already in a database. In many cases, when a user is ‘signing up’ for a web site, he/she is asked to choose a username and password. Here, you will see how to use the SQL Managed Provider to query the database BEFORE inserting the user id into the database.

To see a code sample of how to insert data from a form, into a database, check out this sample:
Inserting Record into Database.

Here, we just use the Employees Table of the Northwind Database, but we add a UID (and password, if you want to complete the functionality) column/field to the table.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.2">
	<title>Checking User ID in Database</title>
<script language="VB" runat="server">
Dim intCount as Integer

Sub doCheck(Source as Object, E as EventArgs)
Dim strConn as string = "server=YourServer;uid=YourUID;pwd=YourPWD;database=YourDB"
Dim MySQL as string = "Select Count(uid) from Employees where uid=@uid"
Dim MyConn as New SQLConnection(strConn)
Dim Cmd as New SQLCommand(MySQL, MyConn)
cmd.Parameters.Add(New SQLParameter("@uid", txtuid.text))
MyConn.Open()
intCount=Cmd.ExecuteScalar
MyConn.Close
	if intCount>0 then
		label1.text="Sorry, that user id is already taken. Try another"
	else
		label1.text ="The user id you chose is not being used "
		''here, you would insert the user information into the database
	End If
End Sub

</script>
</head>
<body>
<Form id="form1" runat="server">
Enter User Name and Password you would like to use:<br>
<table>	<tr>
		<td align="Right" valign="Top">User ID: </td>
		<td align="Left" valign="Top"><asp:TextBox id="txtUID" runat="server" /></td></tr>
	<tr>
		<td align="Right" valign="Top">PWD: </td>
		<td align="Left" valign="Top"><asp:TextBox id="txtPWD" runat="server" /></td>
	</tr>
		<tr>
		<td align="right" valign="Top" Colspan="2"><asp:Button id="button1" Text="Submit" onclick="doCheck" runat="server" /></td>
	</tr>
</table>
<asp:Label ID="label1"  runat="server" />
</Form>
</body>
</html>