Enhanced DataBase Linked Calendar

This is an enhanced version of the other code sample showing how to do basic linking between a calendar and a database. In this example, we add one more field (Title) to the database table, which will then be shown in the appropriate day on the calendar. Also, this sample shows several other properties available to the Calendar control.

Again, we use the SQL Server Managed Provider for this example. The Table used is called CalSchedule, and the columns/fields are
ID (identity), CalDate (DateTime), Schedule(Text), and Title(varchar/50).
If you were using the OleDb Managed Provider, you would use:
ID (autonumber), CalDate (DateTime), Schedule(Memo), and Title(text).
(Data entered online will default to ‘Test Data’ for the Title).

To see an OleDb version of this code, to work with MS Access, click here.

Using Panels to Separate Form Sections

Sometimes a form is too long to include on one page and it would look much nicer if it was broken down into several ‘sections’. Wizards in the Windows Application world are much like this – decisions are broken up into multiple dialog boxes, taking the user from one to the next as choices are made.

This example shows how to do this with a form, breaking it up into multiple sections, keeping the output ‘cleaner’ for the end-user. In order to do this, panels are created. In this sample, there are four panels separating the different sections of the form. As a button is pressed to go from one section to the next, the old one is made invisible, and the next one is made visible. This is such a great concept. It’s not only simple to implement, but it’s also fairly simple to understand. Everything is still on one page, but the end-user never knows any different.

<html>
<head>
<script language="VB" runat="server">
Sub Close1Open2(Source as Object, E as EventArgs)
	pnl1.visible="false"
	pnl2.visible="true"
	pnl3.visible="false"
	pnl4.visible="false"
End Sub

Sub Close2Open3(Source as Object, E as EventArgs)
	pnl1.visible="false"
	pnl2.visible="false"
	pnl3.visible="true"
	pnl4.visible="false"
End Sub

Sub Close3Open4(Source as Object, E as EventArgs)
	pnl1.visible="false"
	pnl2.visible="false"
	pnl3.visible="false"
	pnl4.visible="true"
End Sub

Sub doInsert(Source as Object, E as EventArgs)
	pnl4.visible="false"
	litResponse.text+="<b><i>Thank you -- Your data has been entered</i></b>.<p>"
	litResponse.text+="<i>Here''s what you entered:</i><p>"
	litResponse.text+="<b>First Name</b>: " & frmFname.text & "<br>"
	litResponse.text+="<b>Last Name</b>: " & frmLname.text & "<br>"
	litResponse.text+="<b>Address</b>: " & frmAddress.text & "<br>"
	litResponse.text+="<b>City</b>: " & frmCity.text & "<br>"
	litResponse.text+="<b>State</b>: " & frmState.text & "<br>"
	litResponse.text+="<b>Zip</b>: " & frmZip.text & "<br>"
	litResponse.text+="<b>Phone</b>: " & frmPhone.text & "<br>"
	litResponse.text+="<b>Email</b>: " & frmEmail.text & "<br>"
	litResponse.text+="<b>Employer</b>: " & frmFname.text & "<br>"
	litResponse.text+="<b>Web Site</b>: " & frmwebsite.text & "<br>"
	litResponse.text+="<b>Favorite Color</b>: " & frmFavColor.text & "<br>"
	litResponse.text+="<b>Favorite Band</b>: " & frmFavBand.text & "<br>"
	litResponse.text+="<b>User ID</b>: " & frmUID.text & "<br>"
	litResponse.text+="<b>Pwd</b>: " & frmPWD.text & "<p>"
	litResponse.text+="<i>Here, you also could have inserted the entries " & _
"into a database, emailed them to the user, " & _
"or just about anything else you would need to do</i>."
End Sub
</script>
	<meta name="GENERATOR" Content="ASP Express 2.2">
	<title>Using Panels to Separate Form Sections</title>
</head>
<body>
<form Name="form1" runat="server">
<table>
<asp:Panel ID="pnl1"  runat="server">
	<tr>
		<td align="right">Fname</td>
		<td> <asp:textbox id="frmFname" runat="server" />
		</td>
	</tr>
	<tr>
		<td align="right">Lname</td>
		<td> <asp:textbox id="frmLname" runat="server" />
		</td>
	</tr>
	<tr>
		<td align="right">Address</td>
		<td> <asp:textbox id="frmAddress" runat="server" />
		</td>
	</tr>
	<tr>
		<td align="right">City</td>
		<td> <asp:textbox id="frmCity" runat="server" />
		</td>
	</tr>
	<tr>
		<td align="right">State</td>
		<td> <asp:textbox id="frmState" runat="server" />
		</td>
	</tr>
	<tr>
		<td align="right">Zip</td>
		<td> <asp:textbox id="frmZip" runat="server" />
			<asp:Button id="btnNext"
			Text="Next"
			onclick="Close1Open2"
			runat="server" />
		</td>
	</tr>
</asp:Panel>

<asp:Panel ID="pnl2" visible="false" runat="server">
	<tr>
		<td align="right">Phone</td>
		<td> <asp:textbox id="frmPhone" runat="server" />
		</td>
	</tr>
	<tr>
		<td align="right">Email</td>
		<td> <asp:textbox id="frmEmail" runat="server" />
		</td>
	</tr>
	<tr>
		<td align="right">Employer</td>
		<td> <asp:textbox id="frmEmployer" runat="server" />
		<asp:Button id="btnNext2"
		Text="Next"
		onclick="Close2Open3"
		runat="server" /></td>
	</tr>
</asp:Panel>

<asp:Panel ID="pnl3" visible="false" runat="server">
	<tr>
		<td align="right">WebSite</td>
		<td> <asp:textbox id="frmWebSite" runat="server" />
		</td>
	</tr>
	<tr>
		<td align="right">Favorite Color</td>
		<td> <asp:textbox id="frmFavColor" runat="server" />
		</td>
	</tr>
	<tr>
		<td align="right">Favorite Band</td>
		<td> <asp:textbox id="frmFavBand" runat="server" />
		<asp:Button id="btnNext3"
		Text="Next"
		onclick="Close3Open4"
		runat="server" /></td>
	</tr>
</asp:Panel>

	<tr>
<asp:Panel ID="pnl4" visible="false" runat="server">
		<td align="right">UID</td>
		<td> <asp:textbox id="frmUID" runat="server" />
		</td>
	</tr>
	<tr>
		<td align="right">PWD</td>
		<td> <asp:textbox id="frmPWD"
			textmode="password"
			runat="server" />
		</td>
	</tr>
	<tr>
		<td align="right">
		<asp:button id="button1"
		onclick="doInsert"
		Text="Submit"
		runat="server" /></td>
		<td></td>
	</tr>
</asp:Panel></table>
<div align="left"><asp:Literal ID="litResponse" runat="server"></asp:literal></div>
</form>
</body>
</html>

Linking a Calendar To a Database

This sample uses the SQL Server Managed Provider to link with an ASP.Net Calendar Server Control. Here, we see how to do several things:

  • Set up a simple User Schedule
  • Enable and Disable Controls (LinkButtons)
  • See how to access the Date, Month and Year from the Date clicked in the Calendar

The Table used is called CalSchedule, and the columns/fields are ID (identity), CalDate (DateTime), and Schedule(Text).

A full tutorial will be coming for this soon.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.2">
	<title>Linking a DataBase to a Calendar</TITLE>
<script language="VB" runat="server">
Dim sSchedule as String
Dim sqlSave as String
Dim blData as Boolean
Dim MySQL as String
Sub Calendar_Click(Source as Object, E as EventArgs)
	ph1.visible=true
	litSchedule.text=""
	Dim strConn as string = "server=(local);uid=YourUID;pwd=YourPWD;database=YourDataBase"
	MySQL = "Select CalDate, Schedule from CalSchedule " & _
	"Where CalDate = @caldate "
	Dim MyConn as New SQLConnection(strConn)
	Dim objDR as SQLDataReader
	Dim Cmd as New SQLCommand(MySQL, MyConn)
	cmd.Parameters.Add(New SQLParameter("@caldate", calendar1.selectedDate))
	MyConn.Open()
	objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
	if objDR.Read=True then
		MyConn.Close
		MyConn.Open
		objDR.Close
		objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
		While objDR.Read()
			sSchedule=objDR("Schedule")
			if sSchedule="" then
				litSchedule.text="(<i>Nothing scheduled for this day</i>)"
			else
				sSchedule=sSchedule.Replace(vbcrlf, "<br>")
				litSchedule.text= sSchedule

			End If
		End While
	Else
		litSchedule.text="(<i>Nothing scheduled for this day</i>)"
	End if
	lblFullDate.text=Calendar1.SelectedDate.ToShortDateString
	lblStatus.visible="false"
	lblDate.text=Calendar1.selectedDate.Day
	lblMonth.text=Calendar1.selectedDate.Month
	lblyear.text=Calendar1.selectedDate.Year

End Sub
Sub Admin_Click(Source as Object, E as EventArgs)
	lblNewDate.text=calendar2.selectedDate.ToShortDateString
	lblStatus.visible="false"
	txtinfo.text=""
	Dim strConn as string = "server=(local);uid=YourUID;pwd=YourPWD;database=YourDataBase"
	Dim MySQL as string = "Select CalSchedule.CalDate, CalSchedule.Schedule from " & _
	"CalSchedule Where CalDate = @caldate "
	Dim MyConn as New SQLConnection(strConn)
	Dim objDR as SQLDataReader
	Dim Cmd as New SQLCommand(MySQL, MyConn)
	cmd.Parameters.Add(New SQLParameter("@caldate", lblNewDate.text))

	MyConn.Open()
	objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
	if objDR.Read=True then
		MyConn.Close
		MyConn.Open
		objDR.Close
		objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
		While objDR.Read()
		   litSchedule.text=objDR("calDate") & " : <br>" & objDR("Schedule")
		txtInfo.text=objDR("Schedule")
		blData="True"
		End While
	else
		blData="False"
	End if
	lblSave.text=blData
End Sub

Sub doAdmin(Source as Object, E as EventArgs)
	ph2.visible=true
	lnkNormal.enabled=true
	lnkAdmin.enabled=false
	Calendar1.Visible=false
	Calendar2.visible=true
	''ph1.visible=false
	litSchedule.text=""
End Sub

Sub doNormal(Source as Object, E as EventArgs)
	lnkNormal.enabled=false
	lnkAdmin.enabled=true
	Calendar1.Visible=true
	Calendar2.visible=false
	ph2.visible=false
	ph1.visible=true
	litSchedule.text=""
End Sub

Sub doSave(Source as Object, E as EventArgs)
	if lblSave.text="True" then
		sqlSave = "Update CalSchedule Set calDate=@caldate, schedule=@schedule " & _
		"where caldate=@caldate"
	else
		sqlSave= "Insert into CalSchedule (calDate, schedule) values(@caldate, @schedule)"
	End If
	Dim strConn as string = "server=(local);uid=YourUID;pwd=YourPWD;database=YourDataBase"
	Dim MyConn as New SQLConnection(strConn)
	Dim Cmd as New SQLCommand(sqlSave, MyConn)
		cmd.Parameters.Add(New SQLParameter("@caldate", lblNewDate.text))
		cmd.Parameters.Add(New SQLParameter("@schedule", txtInfo.text))
	MyConn.Open()
	Cmd.ExecuteNonQuery
	MyConn.Close
	lblStatus.visible="true"
	lblStatus.text="Your Data has been entered"
	txtInfo.text=""
	blData="False"
	lblSave.text=blData
End Sub
</script>
</head>
<body><Form id="form1" runat="server">
<asp:LinkButton id="lnkAdmin"
Text="Admin"
onclick="doAdmin"
runat="server" />

<asp:LinkButton id="lnkNormal"
enabled="false"
Text="Normal"
onclick="doNormal"
runat="server" />
<table border="0">
	<tr>
		<td align="left" width="500" valign="Top">
			<asp:Calendar runat="server"
			id="calendar1"
			Backcolor="White"
			Forecolor="Black"
			Borderwidth="2"
			OnselectionChanged="Calendar_Click"
			ShowGridLines="true"
			Width="500" />

			<asp:Calendar id="Calendar2"
			runat="server"
			Backcolor="White"
			BorderColor="blue"
			Forecolor="Black"
			Visible="false"
			Borderwidth="2"
			OnselectionChanged="Admin_Click"
			ShowGridLines="true"
			Width="500" />
		</td>
		<td align="Left" valign="Top">
		<asp:placeholder ID="ph1"  runat="server" visible="false">
		<b>Month:</b><asp:Label ID="lblMonth"  runat="server" /><br>
		<b>Date: </b><asp:Label ID="lblDate"  runat="server" /><br>
		<b>Year: </b> <asp:Label ID="lblYear"  runat="server" /><br>
		<b>Short Date: </b><asp:Label ID="lblFullDate"  runat="server" /><p>
		<b>Schedule for the Day:</b><br>
		<asp:Literal ID="litSchedule" runat="server"></asp:literal>
		</asp:placeholder>
		</td>
	</tr>
</table>
<asp:placeholder ID="ph2" visible="false" runat="server">
	<b><i>Date:</i> </b><asp:Label ID="lblNewDate"  runat="server" /><br>
	<b><i>Enter Schedule:</i></b><br>
	<asp:TextBox id="txtInfo"
	TextMode="MultiLine"
	rows=10
	width=600
	runat="server" />
	<asp:Button id="btnSave"
	Text="Save"
	onclick="doSave"
	runat="server" />
</asp:placeholder>

</Form>
<br>
<i><b><asp:Label ID="lblStatus" runat="server" /></b></i>
<asp:Label ID="lblSave" Visible="false" runat="server" />
</body>
</html>

3 DropDownLists Dynamically

This example uses the OleDb Managed Provider to show how to :
1. Fill a DropDownList based on the choice from another (3 total Dropdownlists)
2. Make a Table Cell Visible or Invisible
3. Use a Literal Control to add text to the page
4. Use of the AutoPostBack property with the DropDownLists
(updated 1/16/2003 – added ‘Choose’ item in DropDownLists – more logical functionality when re-choosing Vehicle types)

If you would like to download the .mdb (MS Access) file to work with, click here. It is a Zipped file, so you will need an unzipping applicationn such as Winzip to unzip it.

<%@ Page Language="VB" Debug="True" Trace="false" TraceMode="SortByCategory" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.2">
	<title>DropDownLists</title>
<script language="VB" runat="server">
Dim strConn as String

Sub Page_Load(Source as Object, E as EventArgs)
strConn="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & server.mappath("\data\auto.mdb") & ";"
if not Page.IsPostBack then
	Dim MySQL as string = "Select Distinct vehicle_type from model"
	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)
	ddl1.DataSource = objDR
	ddl1.DataBind()
	ddl1.items.insert(0,"-- Choose --")
end if
ddl1.items.insert(0,"-- Choose --")
End Sub

Sub fillModel(Source as Object, E as EventArgs)
if ddl1.selectedItem.text <> "-- Choose --" then
	Dim MySQL as string = "Select Model from model where vehicle_type=''" & ddl1.selecteditem.text & "''"
	Dim Myconn as New OleDbConnection(strConn)
	Dim Cmd as New OleDbCommand(MySQL, MyConn)
	MyConn.Open()
	ddl2.DataSource = Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
	ddl2.DataBind()
''	ddl2.selectedindex=0
	tdmodel.visible="true"
	lit1.text="<b>Vehicle Type</b>: " & ddl1.selectedItem.text
        ddl2.items.insert(0,"-- Choose --")
        tdStyle.visible="false"
End If
End Sub

Sub Fillddl3(Source as Object, E as EventArgs)
	DoFill
End Sub

Sub Fill2(Source as Object, E as EventArgs)
	Dim MySQL as string = "Select bodystyle from bodystyle where modelID =''" & ddl2.selecteditem.text & "''"
Dim Myconn as New OleDbConnection(strConn)
	Dim Cmd as New OleDbCommand(MySQL, MyConn)
	MyConn.Open()
	ddl3.DataSource = Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
	ddl3.DataBind()
	tdStyle.visible="true"
	tdLit.visible="true"
	lit1.text="<b>Vehicle Type</b>: " & ddl1.selectedItem.text
	lit1.text+="<br><b>Model</b> : " & ddl2.selecteditem.text
        ddl3.items.insert(0,"-- Choose --")
End Sub

Sub DoFill()
	Dim strConn as string = "server=(local);uid=sa;pwd=password;database=yourdatabase"
	Dim MySQL as string = "Select bodystyle from bodystyle where modelID =''" & ddl2.selecteditem.text & "''"
	Dim MyConn as New OleDbConnection(strConn)
	Dim Cmd as New OleDbCommand(MySQL, MyConn)
	MyConn.Open()
	ddl3.DataSource = Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
	ddl3.DataBind()
	lit1.text="<b>Vehicle Type</b>: " & ddl1.selectedItem.text
	lit1.text+="<br><b>Model</b> : " & ddl2.selecteditem.text
End Sub

Sub doStyle(Source as Object, E as EventArgs)
	lit1.text="<b>Vehicle Type</b>: " & ddl1.selectedItem.text
	lit1.text+="<br><b>Model</b> : " & ddl2.selecteditem.text
	Lit1.text+="<br><b>Body Style</b> :" & ddl3.selecteditem.text
End Sub
Sub startOver(Source as Object, E as EventArgs)
	tdModel.visible="false"
	tdStyle.visible="false"
	lit1.text=""
	tdLit.visible="false"
End Sub
</script>
</head>
<body>
<div align="center"><Form id="form1" runat="server">
<table border="0" runat="server" id="tbl1">
   <tr runat="server">
      <td align="Left" valign="Top" runat="server"><b>Choose Vehicle Type:</b><br>
<asp:DropDownList id="ddl1"
Datatextfield="vehicle_type"
autopostback="true"
onselectedindexchanged="fillModel"
runat="server" />
      </td>
      <td align="Left" valign="Top" runat="server" id="tdModel" visible="false"><b>Choose Model:</b><br>
<asp:DropDownList id="ddl2"
datatextfield="Model"
onselectedindexchanged="Fill2"
autopostback="true"
runat="server" />
      </td>
      <td align="Left" valign="Top" runat="server" id="tdStyle" visible="false"><b>Body Styles</b><br>
<asp:DropDownList id="ddl3"
Datatextfield="BodyStyle"
autopostback="true"
onselectedindexchanged="doStyle"
runat="server" />
      </td>
   </tr>
	<tr>
		<td align="Center" valign="Top" Colspan="4" runat="server" id="tdLit" visible="false">
<hr>
<asp:Literal ID="lit1" runat="server"></asp:literal><hr>
<asp:Button id="btn1"
Text="Start Over"
onclick="startOver"
runat="server" /></td>
	</tr>
</table>
</Form>
</div>

</body>
</html>

Checkboxes In a Datagrid (Check All)

You’ve seen them – a web page/a form/whatever, with checkboxes so you can enter your choices. Sometimes, you need to select all of them. Sometimes, you click the button to select all and you change your mind, so you need to start over by unselecting them all.

This code sample uses the Employees table of the Northwind database, to show you how to accomplish this in a DataGrid. To make this work on your system, just copy the code to your new page, change the provider/connection information and run it.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.2">
	<title>Checkboxes in a DataGrid - Check All</title>
<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
Dim strConn as string = "server=YourSever;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 doChecks(Source as Object, E as EventArgs)
Dim GridItem As DataGridItem
        For Each griditem In MyDataGrid.Items
            Dim myCheckbox As CheckBox = CType(griditem.Cells(0).Controls(1), CheckBox)
            myCheckbox.Checked = True
        Next
End Sub

Sub doUncheck(Source as Object, E as EventArgs)
Dim GridItem As DataGridItem
        For Each griditem In MyDataGrid.Items
            Dim myCheckbox As CheckBox = CType(griditem.Cells(0).Controls(1), CheckBox)
            myCheckbox.Checked = False
        Next
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:BoundColumn DataField="FirstName" HeaderText="FirstName">
		</asp:BoundColumn>
		<asp:BoundColumn DataField="LastName" HeaderText="LastName">
		</asp:BoundColumn>
		<asp:BoundColumn DataField="Title" HeaderText="Title">
		</asp:BoundColumn>
		<asp:BoundColumn DataField="HireDate" HeaderText="HireDate">
		</asp:BoundColumn>
	</Columns>
</asp:DataGrid>

<asp:Button id="btnCheck" Text="Check All" onclick="doChecks" runat="server" />
<asp:Button id="btnUnCheck" Text="Un-Check All" onclick="doUncheck" runat="server" />
</form>
</body>
</html>

DataBase Record Navigation (Next/Prev)

There have been many requests for this particular type of example in the newsgroups and forums. What we’re doing here is doing a representation of the classic Windows app which accesses a database, moving to the first record of a table when it runs. Then, the user can navigate from one record to the next (or also to the first or last record, in this case) with the mere click of a button.

We’re using the SQL Server managed provider, accessing the Northwind Database Employee Table (though here, it is altered/edited by other processes in the code samples, of course).

When the app first starts, it accesses the Minimum and the Maximum ID from the table and uses labels to store the information during the life of the app.

Just copy this to your new file, change the provider/and/or connection info and you’re off and running.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
<script language="VB" runat="server">
Dim intMinID, MinRecNo, MaxRecNo as Integer
Dim sLast, sFirst, sTitle, sHireDate, sAddress, sCity, sExtension, sReportsTo 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 Min(EmployeeID) as MinID, Max(EmployeeID) as MaxID 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)
	While objDR.Read()
		intMinID=objDR("MinID")
		MinRecNo=intMinID
		MaxRecNo=objDR("MaxID")
	End While
	objDR.Close
	doPopulation
	lblID.text=intMinID
	lblMin.text=MinRecNo
	lblMax.text=MaxRecNo

end if
response.Write ("MaxRecNo = " & lblMax.text & "<br>MinRecNo = " & lblMin.text)
End Sub

Sub doPopulation()
	Dim strConn as string = "server=server=YourServer;uid=YourUID;pwd=YourPWD;database=NorthWind"
	Dim MySQL as string = "Select EmployeeID, LastName, FirstName, Title, HireDate, Address, City, " & _
        "Extension from Employees Where EmployeeID =" &  intMinID
	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()
		sLast=objDR("LastName")
		sFirst=objDR("FirstName")
		sTitle=objDR("Title")
		sHireDate=objDR("HireDate")
		sAddress=objDR("Address")
		sCity=objDR("City")
		sExtension=objDR("Extension")
	End While
	frmLastName.text=sLast
	FrmFirstName.text=sFirst
	frmTitle.text=sTitle
	frmHireDate.text=sTitle
	frmAddress.text=sAddress
	frmCity.text=sCity
	frmExtension.text=sExtension
End Sub

Sub doNext(Source as Object, E as EventArgs)
	if cInt(lblID.text)< cInt(lblMax.text) then
		intMinID=Cint(lblID.text) + 1
		lblWarning.text=""
	else
		intMinID=lblID.text
		lblWarning.text= ("<font Color=""#FF0000""><i>You''ve Reached the End of the Records</i></font>")
	End If
	DoPopulation
	lblID.text=intMinID

End Sub

Sub doPrev(Source as Object, E as EventArgs)
	if cInt(lblID.text)>cInt(lblMin.text)then
		intMinID=Cint(lblID.text) - 1
		lblWarning.text=""
	else
		intMinID=lblID.text
		lblWarning.Text= ("<font Color=""#FF0000""><i>You''ve Reached the Beginning of the Records</i></font>")
	End If
	DoPopulation
	lblID.text=intMinID
End Sub

Sub doFirst(Source as Object, E as EventArgs)
	intMinID=cInt(lblMin.text)
	DoPopulation
	lblWarning.Text= ("<font Color=""#FF0000""><i>You''ve Reached the Beginning of the Records</i></font>")
	lblID.text=intMinID
End Sub

Sub doLast(Source as Object, E as EventArgs)
	intMinID=cInt(lblMax.text)
	DoPopulation
	lblWarning.Text= ("<font Color=""#FF0000""><i>You''ve Reached the End of the Records</i></font>")
	lblID.text=intMinID
End Sub
</script>
	<meta name="GENERATOR" Content="ASP Express 2.2">
	<title>Next - Previous Records in a DataBase</title>

</head>
<body>
<form runat="server">
<table>
	<tr>
		<td align="right">Last Name</td>
		<td> <asp:textbox id="frmLastName" runat="server" /></td>
	</tr>
	<tr>
		<td align="right">First Name</td>
		<td> <asp:textbox id="frmFirstName" runat="server" /></td>
	</tr>
	<tr>
		<td align="right">Title</td>
		<td> <asp:textbox id="frmTitle" runat="server" /></td>
	</tr>
	<tr>
		<td align="right">Hire Date</td>
		<td> <asp:textbox id="frmHireDate" runat="server" /></td>
	</tr>
	<tr>
		<td align="right">Address</td>
		<td> <asp:textbox id="frmAddress" runat="server" /></td>
	</tr>
	<tr>
		<td align="right">City</td>
		<td> <asp:textbox id="frmCity" runat="server" /></td>
	</tr>
	<tr>
		<td align="right">Extension</td>
		<td> <asp:textbox id="frmExtension" runat="server" /></td>
	</tr>
	<tr>
		<td align="right"><b>Current Record #: </b>
		<asp:Label ID="lblID" runat="server" />
		</td>
		<td>
		<asp:Button id="btnPrev" Text="<< Previous" onclick="doPrev" runat="server" />
		<asp:Button id="btnNext" Text="Next >>" onclick="doNext" runat="server" />
		</td>
	</tr>
	<tr>
		<td align="Left" valign="Top">
			<asp:Label ID="lblMin"  visible="false" runat="server" />
			<asp:Label ID="lblMax"  visible="false" runat="server" />
		</td>
		<td align="Left" valign="Top">
			<asp:Button id="lblFirst" Text="First" onclick="doFirst" runat="server" />
			<asp:Button id="lblLast" Text="Last" onclick="doLast" runat="server" /><br>
			<asp:Label ID="lblWarning"  runat="server" /><br>
		</td>
	</tr>
</table>
</form>
</body>
</html>

Nested DataLists (C# Version)

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.

You can read a Tutorial about this code here.

Thanks to Mike Houston for this code sample
http://www.nexus6studio.com

See this code in VB.Net

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<HTML>
  <HEAD>
    <title>Nested Datalists Using C#</title>
  <script language=C# runat=server>
  void Page_Load(object sender, System.EventArgs e)
  {
	string strConn = "Server=YourServer;uid=yourUID;pwd=YourPWD;database=Northwind";
	string MySQL = "Select CategoryID, CategoryName from Categories";
	SqlConnection MyConn = new SqlConnection(strConn);
	DataSet ds = new DataSet();

	SqlDataAdapter Cmd = new SqlDataAdapter(MySQL,MyConn);
	Cmd.Fill(ds,"Categories");

	SqlDataAdapter Cmd2 = 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();
  }
  </script>
  </HEAD>
  <body>
    <form id="Form1" method="post" runat="server">
<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><%# DataBinder.Eval(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='<%# DataBinder.Eval(Container, "DataItem.myrelation") %>'
 RepeatColumns="3">
				<ItemTemplate>
					&nbsp; &nbsp; <%# DataBinder.Eval(Container, "DataItem.ProductName") %>
				</ItemTemplate>
			</ASP:DataList>
	</ItemTemplate>
</asp:DataList>
    </form>

  </body>
</HTML>

RadioButtonList with AutoPostback

This sample uses the SQL Managed Provider and the Northwind Database to, based on the selection from the RadioButtonList (Manually populated, in this case), populate a DropDownList with all the Product Names that fall in the selected Category. 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.

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

<%@ 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 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" AutoPostback="true" OnSelectedIndexChanged ="popddl" runat="server">
		<ASP:LISTITEM value="1">Beverages</ASP:LISTITEM>
		<ASP:LISTITEM value="2">Condiments</ASP:LISTITEM>
		<ASP:LISTITEM value="3">Confections</ASP:LISTITEM>
		<ASP:LISTITEM value="4">Dairy Products</ASP:LISTITEM>
		<ASP:LISTITEM value="5">Grains/Cereals</ASP:LISTITEM>
		<ASP:LISTITEM value="6">Meat/Poultry</ASP:LISTITEM>
		<ASP:LISTITEM value="7">Produce</ASP:LISTITEM>
		<ASP:LISTITEM value="8">Seafood</ASP:LISTITEM>
		</asp:RadioButtonList>
		</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>
</html>

Display XLS (Excel) File with DataGrid

This code sample shows how to read an XLS file (Excel) using the OleDb Managed Provider, and then display it, using a DataGrid. For this particular sample, after downloading the Lotto Texas Results in xls file format, I just trimmed it a little for speed and ease of viewing. If no other .xls file is available, you can download the full file here:
Download Lottery file
(You might need to right click on the link and ‘select target’ to download it, if you have Excel installed on your computer)

To make this work on your system, just adjust the path to match your needs on your system.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.1">
	<title>Displaying an XLS file in a DataGrid</title>

<script language="VB" runat="server">
	dim x as integer
Sub Page_Load(Source as Object, E as EventArgs)
	GetXLS()
End Sub

Sub GetXLS()
	Dim strConn as String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\inetpub\wwwroot\lotto.xls;Extended Properties=Excel 8.0;"
	Dim MySQL as String="Select * from [lotto$]"
	Dim Conn As New OleDb.OleDbConnection(strConn)
	Dim da As New System.Data.OleDb.OleDbDataAdapter(MySQL, Conn)
	Dim ds As New DataSet()
	Conn.Open()
	da.Fill(ds, "lotto")
	MyDataGrid.Datasource=ds.Tables(0).DefaultView
	MyDataGrid.DataBind
	conn.close()
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 (12)
	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 (10)
	next
End Select
End Sub
</script>

</head>
<body>

<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"
	BackColor="#8080FF"
	Font-Name="Arial"
	Font-Size="10"
	AlternatingItemStyle-BackColor="#C0C0C0"
	AlternatingItemStyle-Font-Name="Arial"
	AlternatingItemStyle-Font-Size="11"
	BorderColor="Black"
	OnItemDataBound="DataBound">
</asp:DataGrid>
</form>
</div></body>
</html>

Get Last Inserted ID with MS Access

This code sample shows how to grab the last id# after an insert, using older vesions of MS Access (before Access 2000).

The database which is being used, has two tables, one called Items and one called Cateogories. the Items database has an autonumbering ID field, and two other text fields (ItemName and ItemText). The Categories table has two fields (CatID, also Autonumbering, and CatName).

To see a more preferred method, using Access 2000 and above, check out this code sample.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDB" %>
<html>
<head>

<script language="VB" runat="server">
Dim intNewID
Sub Page_Load(Source as Object, E as EventArgs)
Dim strConn as string = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & server.mappath("/data/Newprocedures.mdb") & ";"
Dim MySQL as string = "Select CatID, catName from Categories Order by CatID"
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)
frmCatID.DataTextField="catName"
frmCatID.DataValueField="catID"
frmCatID.DataSource = objDR
frmCatID.DataBind()
MyConn.Close()
End Sub

Sub doInsert(Source as Object, E as EventArgs)
	Dim strConn as string = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & server.mappath("/data/Newprocedures.mdb") & ";"
	Dim MySQL as string = "Insert into Items (itemName, itemText, CatID) Values (@itemName, @itemText, @CatID);"
	Dim MySQL2 as string = "select MAX(ID) from Items"
	Dim MyConn as New OleDbConnection(strConn)
	Dim Cmd as New OleDbCommand(MySQL, MyConn)
	Dim Cmd2 as New OLEDBCommand(MySQL2, MyConn)
	With Cmd.Parameters
		.Add(New OleDbParameter("@itemName", frmitemName.text))
		.Add(New OleDbParameter("@itemText", frmitemText.text))
		.Add(New OleDbParameter("@CatID", frmCatID.selecteditem.value))
	End With
	MyConn.Open()
	cmd.ExecuteNonQuery()
	Label1.text = "It's Done - your information has been inserted!<p>"

	label1.text +="Last ID Inserted = " & cmd2.executescalar()
	MyConn.Close
End Sub

</script>
	<meta name="GENERATOR" Content="ASP Express 2.1">
	<title>Get Last Inserted ID with MS Access</title>
</head>
<body>

<form runat="server">
<table>

	<tr>
		<td align="right">Item Name</td>
		<td> <asp:textbox id="frmitemName" runat="server" /></td>
	</tr>
	<tr>
		<td align="right">Item Text</td>
		<td> <asp:textbox id="frmitemText" runat="server" /></td>
	</tr>
	<tr>
		<td align="right">Category</td>
		<td> <asp:dropdownlist id="frmCatID" runat="server" /></td>
	</tr>
	<tr>
		<td align="right"><asp:button id="button1"  onclick="doInsert" Text="Submit" runat="server" /></td>
		<td></td>
	</tr>
</table>
<asp:Label ID="label1"  runat="server" />
</form>
</body>
</html>