Changing Calendar Year

Without clicking on Previous or Next Month over and over, at first, with the ASP.Net Calendar Control, it seems pretty cumbersome, to change the year of the calendar. This sample shows a simple way of setting up a DropDownlist to work in conjunction with the Calendar Control to quickly Change the year of the Calendar Control.

<script language="VB" Runat="server">
Dim myDate as DateTime
Dim myYear as Long
dim x as Integer
Dim iDiff as Integer
	Sub Page_Load(Source as Object, E as EventArgs)
	myDate=DateTime.Now
	myYear=MyDate.Year

		if not Page.IsPostBack then
			ddlYear.Items.Add(myYear)
			For x=1 to 5
				ddlYear.Items.add(new ListItem(myYear-x))
			next
		end if
	End Sub

	Sub ChangeYear(Source as Object, E as EventArgs)
		iDiff=MyYear-cInt(ddlYear.SelectedItem.text)
		cal1.TodaysDate=myDate.addYears(-iDiff)
	End Sub
</script>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.1">
	<title>Easy Calendar Year Change</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:DropDownList id="ddlYear" Runat="server">
</asp:DropDownList><br>
<asp:Calendar id="cal1" Runat="server"
	Backcolor="White"
	Forecolor="Black"
	Borderwidth="2"
	ShowGridLines="true" />

	<asp:Button id="btn" Text="Change Year"
		onclick="changeYear" Runat="server" />
</form>
</body>
</html>

Using String Properties (Length/SubString/IndexOf)

This sample actually shows quite more things than it looks like, on the surface. For this example, you will need to enter either a basic 5 number Zip Code or a Zip + 4 Zip Code into the text box. There are a couple of things that aren’t covered here. One thing that is NOT included is a numeric character check – so don’t enter any alpha characters. The other thing, obviously is it does not validate the actual Zip Code. (sorry – but no apologies for either one)

Here are the main ideas touched upon here:

  1. Basic use of String Properties (SubString, IndexOf, Length)
  2. Error checking with a RequiredField Validator (ASP.Net Server Control)
  3. Custom Error Checking without an ASP.Net Validator Control.
<script language="VB" Runat="server">
Dim sZip as String
Dim sZip4 as String
Dim sZip5Error as String
Dim sZip4Error as String
Dim intZipIndex as Integer
Sub doConversion(Source as Object, E as EventArgs)
sZip=txtZip5.text
intZipIndex=sZip.IndexOf("-")

if intZipIndex <>-1 then
	sZip4=sZip.Substring(intZipIndex+1)
	if intZipIndex>5 then
		lblError.visible="True"
		sZip5Error="Sorry - You have entered too many numbers in the Zip5 portion"

	elseif intZipIndex<5 then
		lblError.visible="True"
		sZip5Error="Sorry - You haven''t entered enough numbers in the Zip5 portion"

	else
		lblError.visible="False"
		lblZip.text="Zip 5 = " & sZip.Substring(0,intZipIndex) & "<br>Zip 4 = " & sZip4
	End If
	if sZip5Error<>"" then lblerror.text=sZip5Error

	lblResults.text="<i>Found the ''-'' at position</i> " & intZipIndex.ToString

	if sZip4.Length < 4 then
		lblError.Visible="True"
		sZip4Error="<br>Sorry - the Zip 4 portion does not have enough numbers"
	elseif sZip4.Length >4 then
		lblError.Visible="True"
		sZip4Error="<br>Sorry - the Zip 4 portion has too many numbers"
	else
		sZip4Error=""
	End If
	if sZip5Error <>"" then
		lblError.text+=sZip4Error
	else
		lblError.text=sZip4Error
	End If
else
	lblZip.text="Zip = " & sZip
	lblResults.text="<font Color=''#FF0000''><b><i>No ''-'' was found</i></b></font>"
	if sZip.Length<5 or sZip.Length >5 then
		sZip5Error="You do not have the correct number of characters in the Zip Code"
	else
		sZip5Error=""
	End If
	lblError.text=sZip5Error
End If
End Sub

</script>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.0">
	<title>Using String Properties (Length/SubString/IndexOf)</title>
</head>
<body>
	<form id="form1" Runat="server">
	<b><i>Enter Zip Code Here: </i></b>
		<asp:TextBox id="txtZip5" Runat="server" />
		<asp:Button id="btn1"
			Text="Get Zip5/4"
			onclick="doConversion"
			Runat="server" /><br>
		<asp:RequiredFieldValidator ID="vldZip5"
			Font-Italic="True"
			Font-Bold="True"
			ControlToValidate="txtZip5" Display="Dynamic"
			ErrorMessage="Come on - You must put something in the textbox!"
			Runat="server">
		</asp:RequiredFieldValidator>
	<asp:Label ID="lblResults" Runat="server" /><br>
	<asp:Label ID="lblZip" Runat="server" />
	<hr>
	<div align="center">
		<asp:Label ID="lblError"
			ForeColor="Red"
			Visible="True"
			Font-Bold="True"
			Runat="server" />
	</div>
	</form>
</body>
</html>

Simple Math in ASP.Net

Sometimes, it may become necessary to do some form of math in your ASP.Net form. This sample shows an example of both simple addition and subtraction, along with multiplication and division, within a semi-practical application of math in ASP.Net, showing what the proceeds would be from the Powerball Lottery, given an amount entered into a textbox.

<script language="VB" Runat="server">
Dim intLotto, intLottoLump, intLottoLumpTax, intYear, intYearTax as Integer
Sub doAddtion(Source as Object, E as EventArgs)
	if txtAdd1.text <>"" and txtAdd2.text <>"" then
		txtSum.text=Val(txtAdd1.text) + Val(txtAdd2.text)
	End If
End Sub

Sub doSubtraction(Source as Object, E as EventArgs)
	if txtSub1.text <>"" and txtSub2.text <>"" then
		txtSub.text=Val(txtSub1.text) - Val(txtSub2.text)
	End If
End Sub

Sub doCalc(Source as Object, E as EventArgs)
	if txtAmt.text <>"" then
		pnl1.visible=true
		intLotto=CInt(txtAmt.text)*1000000
		intLottoLump =intLotto*.5404762
		intLottoLumpTax=intLottoLump*.72
		intYear=intLotto/30
		intYearTax=intYear*.72
		lblsum.text=FormatCurrency(intLottoLump, 2, True, True, True)
		lblSumTax.text=FormatCurrency(intLottoLumpTax, 2, True, True, True)

		lblYear.text=FormatCurrency(intYear, 2, True, True, True)
		lblYearTax.text=FormatCurrency(intYearTax, 2, True, True, True)
	End If
End Sub

Sub doReset(Source as Object, E as EventArgs)
	txtAmt.text=""
	pnl1.visible="false"
End Sub
</script>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.0">
	<title>Simple Math with ASP.Net</title>
</head>
<body>
<form id="form1" Runat="server">
<div align="center"><font Size="5" Color="#0000FF"><b>Math Samples in ASP.Net</b></font><hr>
<asp:Table ID="tblAdd" Runat="Server" Width="250"
	BorderColor="Black"
	BorderWidth="1"
	CellPadding="0"
	CellSpacing="0">
	<asp:TableRow ID="tblRow1" Runat="Server">
		<asp:TableCell ID="tblCell1" Runat="Server">
			<table>
			<tr>
				<td align="Left" valign="Top" Colspan="2">
				<b><font Size="4" Color="#0000FF">
					Simple Addition:</font>
				</b></td>
			</tr>

			<tr>
				<td align="Right" valign="Top">1st Number :</td>
				<td align="Left" valign="Top">
				<asp:TextBox id="txtAdd1" Width="35" Runat="server" />
				</td>
			</tr>
			<tr>
				<td align="Right" valign="Top" Colspan="2">
				<b><font Size="6" Color="#0000FF">+</font></b></td>
			</tr>
			<tr>
				<td align="Right" valign="Top">2nd Number: </td>
				<td align="Left" valign="Top">
				<asp:TextBox id="txtAdd2" Width="35" Runat="server" /></td>
			</tr>
			<tr>
				<td align="Right" valign="Top">
					<asp:Button id="btnAddition"
						Text="Add Numbers Together"
						onclick="doAddtion"
						Runat="server" />
				</td>
			</tr>
			<tr>
				<td align="Right" valign="Top"><b>Total:</td> </b>
				<td align="Left" valign="Top">
				<asp:TextBox id="txtSum" Width="35" Runat="server" />
				</td>
			</tr>
			</table>
		</asp:TableCell>
		<asp:TableCell ID="tblCell2" Runat="Server">
					<table>
			<tr>
				<td align="Left" valign="Top" Colspan="2">
				<b><font Size="4" Color="#0000FF">
					Simple Subtraction:</font>
				</b></td>
			</tr>

			<tr>
				<td align="Right" valign="Top">1st Number :</td>
				<td align="Left" valign="Top">
				<asp:TextBox id="txtSub1" Width="35" Runat="server" />
				</td>
			</tr>
			<tr>
				<td align="Right" valign="Top" Colspan="2">
				<b><font Size="6" Color="#0000FF">-</font></b></td>
			</tr>
			<tr>
				<td align="Right" valign="Top">2nd Number: </td>
				<td align="Left" valign="Top">
				<asp:TextBox id="txtSub2" Width="35" Runat="server" /></td>
			</tr>
			<tr>
				<td align="Right" valign="Top">
					<asp:Button id="btnSubtraction"
						Text="Subtract Numbers"
						onclick="doSubtraction"
						Runat="server" />
				</td>
			</tr>
			<tr>
				<td align="Right" valign="Top"><b>Total:</td> </b>
				<td align="Left" valign="Top">
				<asp:TextBox id="txtSub" Width="35" Runat="server" /></td>
			</tr>
			</table>
		</asp:TableCell>
	</asp:TableRow>
</asp:Table></div>
<hr>
<div align="center"><font Size="4" Color="#0000FF">PowerBall Calculator</font></div>
<hr>
Enter an amount below, and click on the ''Calculate'' button. 
The PowerBall Calculator will then calculate the lump sum payout
(plus that amount after taxes), along with the 30 yearly payout amount (plus that amount after taxes).<hr>
Enter Amt (in millions) :
<asp:TextBox
	id="txtAmt"
	Width="75"
	runat="server" />
<asp:Button id="btn1"
	Text="Calculate"
	onclick="doCalc"
	runat="server" />
<asp:Button id="reset"
	Text="Reset"
	onclick="doReset"
	runat="server" />

<asp:panel ID="pnl1"  Visible="false" runat="server">
<b>Lump Sum : </b><br>
	 (approx)  <font Color="#FF0000"><asp:Label ID="lblsum"  runat="server" /></font> /
	<asp:Label ID="lblSumTax"  runat="server" /> <i><font Color="#0000FF">(after 28% tax)</font></i>
	<p>
	<b>Per Year (1 initial pymt and equal pymts for 29 additional years) : </b>  <br>
	(approx) <font Color="#FF0000"><asp:Label ID="lblYear"  runat="server" /></font> /
	<asp:Label ID="lblYearTax"  runat="server" /> <i><font Color="#0000FF">(after 28% tax)</font></i>
</asp:panel>
</form>
</body>
</html>

States (US) DropDownList

This sample shows how to use a string to populate a DropDownList with all the US states (plus D.C.).

<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
	doStates
end if
End Sub

Sub doStates()
	Dim sStates() as string={"AK", "AL", "AR", "AZ", "CA", "CO", "CT", "DC", _
	"DE", "FL", "GA", "HI", "IA", "ID", "IL", "IN", "KS", "KY", "LA", "MA", "ME", "MD", _
	"MI", "MN", "MO", "MS", "MT", "NC", "ND", "NE", "NH", "NJ", "NM", "NV", "NY", _
	"OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VA", "VT", _
	"WA", "WI", "WV", "WY"}
	ddlStates.datasource=sStates
	ddlStates.databind()
End Sub
</script>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.0">
	<title>Untitled</title>
</head>
<body>
	<form id="form1" runat="server">
		<asp:DropDownList id="ddlStates" runat="server"/>
	</form>
</body>
</html>

Date/Time in ASP.Net

This sample shows formatting in a couple of different ways, for Date/Time in ASP.Net – and at least most of the different ‘pieces’ that you might need in coding your web pages

<script language="VB" runat="server">
Dim MyDate as New DateTime
Sub Page_Load(Source as Object, E as EventArgs)
MyDate=DateTime.Now

	lblFull.text=MyDate
	lblMonth.text=MyDate.Month
	lblDaysinMonth.Text= MyDate.DaysInMonth(MyDate.Year, MyDate.Month)
	lblDayofMonth.Text= MyDate.Day
	lblDayofWeek.Text= MyDate.DayofWeek.ToString
	lblDate.text= MyDate.Date

	lblD.text=MyDate.ToString("D") ''Long Date
	lblTime.text=MyDate.ToString("t")
	lblLongTime.text=MyDate.ToLongTimeString
	lblHour.text=MyDate.Hour
	lblMinute.text=MyDate.Minute
	lblSecond.text=MyDate.Second
End Sub

</script>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.0">
	<title>Date/Time in ASP.Net</title>
</head>
<body>
<form id="form1" runat="server">
<table width="100%">	<tr>
		<td align="Left" valign="Top"><b>DateTime.Now:</b>
<asp:Label ID="lblFull"  runat="server" /><br>
<b>Month: </b> <asp:Label ID="lblMonth"  runat="server" /><br>
<b>Days in Month:</b> <asp:Label ID="lblDaysinMonth"  runat="server" /><br>
<b>Day of Month:</b> <asp:Label ID="lblDayofMonth"  runat="server" /><br>
<b>Day of Week:</b> <asp:Label ID="lblDayofWeek"  runat="server" />
		</td>
		<td align="Left" valign="Top"><b>Short Date: </b>
<asp:Label ID="lblDate"  runat="server" /><br>
<b>Long Date </b> <asp:Label ID="lblD"  runat="server" /><br>
<b>Time: </b> <asp:Label ID="lblTime"  runat="server" /><br>
<b>LongTime:</b> <asp:Label ID="lblLongTime"  runat="server" /><br>
<b>Hour: </b>
<asp:Label ID="lblHour"  runat="server" /><b> - Minute: </b>
<asp:Label ID="lblMinute"  runat="server" /><b> - Second: </b>
<asp:Label ID="lblSecond"  runat="server" />
		</td>
	</tr>
</table>
</form>
</body>
</html>

CheckBoxList – Selecting Multiple Items

This code sample shows how to retrieve the selected (checked) items from a CheckBoxList Server control, with multiiple items selected

<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.0">
	<title>CheckBoxList - Selecting Multiple Items</title>
<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
	if not Page.IsPostBack then
		with cbList.items
			.add ("Cherry")
			.add ("Vanilla")
			.add ("Strawberry")
			.add ("Chocolate")
			.add ("Banana")
			.add ("Apple")
		end with
	end if
End Sub

Sub doList(Source as Object, E as EventArgs)
        Dim Stuff As String
        Dim Item As ListItem
        For Each Item In CBList.Items
            If Item.Selected Then
                Stuff = Stuff & Item.Text & "<br>"
            End If
        Next
        If Stuff <> "" Then
            Label1.Text = "<b><font Color=''#0000FF''>You chose :</font></b>  <br>" & Stuff
        Else
            Label1.Text = "<b>Hey - Nothing was chosen!</b> "
        End If
End Sub

</script>
</head>
<body>
<Form id="form1" runat="server">
<table>	<tr>
		<td align="Left" valign="Top">
			<asp:CheckBoxList id="cbList"
				Height="125px"
				width="100px"
			 	runat="server" />
			<asp:Button id="button1"
				Text="Get Items"
				onclick="doList"
				runat="server" />
		</td>
		<td align="Left" valign="Top">
			<asp:Label ID="label1"
				Font-Italic="True"
				ForeColor="Red"
				runat="server" />
		</td></tr>
</table>
</Form>
</body>
</html>

Changing Control Properties with CSS

This code sample uses a textbox to show how easily it is to change Server Control Properties using CSS. The format is:
[control].style(“cssStyleGoesHere”)=”StyleDesignationGoesHere”

<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
	if not Page.IsPostBack then
		myText.Style("font-family") = "Arial"
	end if
End Sub
Sub doBold(Source as Object, E as EventArgs)
	mytext.style("font-weight")="bold"
End Sub
Sub doColor(Source as Object, E as EventArgs)
	myText.Style("color") = ddlColor.selecteditem.text
End Sub
Sub doSize(Source as Object, E as EventArgs)
	mytext.style("font-size")=ddlSize.selecteditem.text
End Sub
Sub doBackColor(Source as Object, E as EventArgs)
	myText.Style("backGround") = ddlBackColor.selecteditem.text
End Sub

</script>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.0">
	<title>Changing Control Properties with CSS</title>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox id="myText"
	TextMode="SingleLine"
	Text="This is the text in my Text Box"
	Width="350" Rows="10" runat="server" />
<asp:Button id="btn"
	Text="Make Bold"
	onclick="doBold"
	runat="server" /><br>
<table>	<tr>
		<td align="Right" valign="Top">
		<b>ForeColor:</b><br>
		<asp:DropDownList id="ddlColor" runat="server">
			<asp:listitem>AntiqueWhite</asp:listitem>
			<asp:listitem>Aqua</asp:listitem>
			<asp:listitem>Azure</asp:listitem>
			<asp:listitem>Bisque</asp:listitem>
			<asp:listitem>Blue</asp:listitem>
			<asp:listitem>Brown</asp:listitem>
			<asp:listitem>Coral</asp:listitem>
			<asp:listitem>CornSilk</asp:listitem>
			<asp:listitem>Red</asp:listitem>
			<asp:listitem>Pink</asp:listitem>
			<asp:listitem>DarkGreen</asp:listitem>
			<asp:listitem>DarkBlue</asp:listitem>
			<asp:listitem>Green</asp:listitem>
		</asp:DropDownList>
		</td>
		<td align="Left" valign="Bottom">
		<asp:Button id="btnColor"
			Text="Change ForeColor"
			onclick="doColor"
			runat="server" /></td>
	</tr>
	<tr>
		<td align="Right" valign="Top">
		<b>Back Color:</b><br>
		<asp:DropDownList id="ddlBackColor" runat="server">
			<asp:listitem>AntiqueWhite</asp:listitem>
			<asp:listitem>Aqua</asp:listitem>
			<asp:listitem>Azure</asp:listitem>
			<asp:listitem>Bisque</asp:listitem>
			<asp:listitem>Blue</asp:listitem>
			<asp:listitem>Brown</asp:listitem>
			<asp:listitem>Coral</asp:listitem>
			<asp:listitem>CornSilk</asp:listitem>
			<asp:listitem>Red</asp:listitem>
			<asp:listitem>Pink</asp:listitem>
			<asp:listitem>DarkGreen</asp:listitem>
			<asp:listitem>DarkBlue</asp:listitem>
			<asp:listitem>Green</asp:listitem>
		</asp:DropDownList>
		</td>
		<td align="Left" valign="Bottom">
                 <asp:Button
                 id="btnBackColor"
                 Text="Change
                 BackColor"
                 onclick="doBackColor"
                 runat="server" /></td>
	</tr>
	<tr>
		<td align="Right" valign="Bottom"><b>Font Size:</b><br>
		<asp:DropDownList id="ddlSize" runat="server">
			<asp:listitem>8</asp:listitem>
			<asp:listitem>10</asp:listitem>
			<asp:listitem>12</asp:listitem>
			<asp:listitem>14</asp:listitem>
			<asp:listitem>18</asp:listitem>
			<asp:listitem>24</asp:listitem>
			<asp:listitem>36</asp:listitem>
			<asp:listitem>48</asp:listitem>
		</asp:DropDownList></td>
		<td align="left" valign="Bottom">
		<asp:Button id="btnSize"
			Text="Change Size"
			onclick="doSize"
			runat="server" /></td>
	</tr>
</table>
</form>
</body>
</html>

Dynamically Adding Dates to DropDownList

This code sample shows how to start with today’s date, and dynamically, add the previous two weeks worth of dates to a DropDownList.

Along with that, it shows how to insert an item as the top component (like ‘– Select Date –’) in a DropDownList, as well as how to select an item from the list. As a bonus, we add in an example of changing the font colors in a Label, based on the selection in the DropDownList.

<%@ Import Namespace="System.Drawing" %>
<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
Dim sDate as DateTime
Dim x as Integer
sDate=DateTime.Now.ToShortDateString()
ddl.items.add(new ListItem(sDate))
For x=1 to 14
ddl.Items.add(new ListItem(sDate.adddays(-x)))
next
ddl.items.insert(0,"– Select Date –")
end if
End Sub

Sub ChooseDate(Source as Object, E as EventArgs)
if ddl.selecteditem.text <> "– Select Date –"
label1.text = "The Date you chose was : " & ddl.selecteditem.text
label1.forecolor=color.Blue
else
label1.text="You must select a date"
label1.forecolor=color.Red
End If
End Sub
</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 3.0b1">
<title>Dynamically Adding Dates to DropDownList</title>
</head>
<body>
<div align="center">
<form id="form1" runat="server">
<asp:DropDownList id="ddl" runat="server" />
<asp:Button id="button1"
Text="Choose Date"
onclick="ChooseDate"
runat="server" />
</form>
<asp:Label ID="label1" runat="server" />
</div>
</body>
</html>

Showing Images in a DataGrid based on Database Data

This sample uses the OleDb managed provider for connecting to an MS Access database. In this Products database, we have a an ID field, Product Name, Comments and an image name.

We use a datagrid for the display purposes, using both BoundColumns and TemplateColumns. In the TemplateColumn, we include an HTML image tag, and have the source of the tag point to a path where our images are located, and then, we use the data from the ImageName field in the database to finish it off.

You can download the database and the images in This File

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDB" %>
<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("\data\products.mdb") & ";"
	Dim MySQL as string = "Select * from Products"
	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)
	dg.DataSource = objDR
	dg.DataBind()
End Sub
</script>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.0b1">
	<title>Showing Images in a DataGrid based on Database Data</title>
</head>
<body>
<form id="form1" runat="server">
<div align="center"><asp:Datagrid runat="server"
	Id="dg"
	GridLines="Both"
	cellpadding="0"
	cellspacing="0"
	Headerstyle-BackColor="#8482C6"
	Headerstyle-Forecolor="#0F0F0F"
	Headerstyle-Font-Name="Arial"
	Headerstyle-Font-Bold="True"
	Headerstyle-Font-Size="12"
	BackColor="#C6C3FF"
	Font-Name="Arial"
	Font-Size="10"
	BorderColor="Black"
	 AutoGenerateColumns="False">
<columns>
<asp:BoundColumn HeaderStyle-HorizontalAlign="Center" DataField="ProdName" HeaderText="ProdName"></asp:BoundColumn>
	<asp:TemplateColumn HeaderStyle-HorizontalAlign="Center">
	<HeaderTemplate>
		Images
	</HeaderTemplate>
	<ItemTemplate>
<div align="center">
	<IMG SRC=''/prodimages/<%# Container.DataItem("ImageName") %>'' Border="0"><br>
	<%# Container.DataItem("ImageName") %>
</div>
	</ItemTemplate>
	</asp:TemplateColumn>
<asp:BoundColumn DataField="Comments" HeaderText="Comments"></asp:BoundColumn>
</columns>
</asp:DataGrid></div>
</form>
</body>

Inserting Records into MS Access

This is basically the same code sample as another SQL Server example. Only the Managed Provider has been changed to OleDb, so that it will work with MS Access.

If you want to try this at home — download the mdb file to work with it on your computer, by Clicking Here. Then, copy this code into your new aspx page.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<script language="VB" runat="server">
Dim strFname, strLname as string

Sub doInsert(Source as Object, E as EventArgs)
	Dim MySQL as string = "Insert into testInsert (fname, lname) values (@Fname, @Lname)"
	Dim myConn As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & _
	 "Data Source=" & server.mappath("\Data\TestInsertDB.mdb") & ";"	)
	Dim Cmd as New OleDbCommand(MySQL, MyConn)
	cmd.Parameters.Add(New OleDbParameter("@Fname", frmfname.text))
	cmd.Parameters.Add(New OleDbParameter("@Lname", frmlname.text))
	MyConn.Open()
	cmd.ExecuteNonQuery
	MyConn.Close()
	label1.visible="true"

	BindData()
	label1.text = "Your data has been received!"
End Sub

Sub viewthem(Source as Object, E as EventArgs)
mydatagrid.visible="true"
label1.visible="false"
	BindData
End Sub

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

Sub BindData()
	Dim MySQL as string = "Select * from testInsert order by id desc"
	Dim myConn As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & _
	 "Data Source=" & server.mappath("\Data\TestInsertDB.mdb") & ";"	)
	Dim ds as DataSet=New DataSet()
	Dim Cmd as New OleDbDataAdapter(MySQL,MyConn)
	Cmd.Fill(ds,"testInsert")
	MyDataGrid.Datasource=ds.Tables("testInsert").DefaultView
	MyDataGrid.DataBind()
	MyConn.Close()
End Sub

Sub cleartextboxes(Source as Object, E as EventArgs)
	Dim myForm As Control = Page.FindControl("form1")
	Dim ctl As Control
	For Each ctl In myForm.Controls
		If ctl.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox") Then
			CType(ctl, TextBox).Text = ""
		End If
	Next ctl
End Sub
</script>

<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.0">
	<title>Inserting Records into MS Access</title>
</head>
<body>
<Form id="form1" runat="server">
<table border="0">
	<tr>
		<td align="right">fname</td>
		<td> <asp:textbox id="frmfname" runat="server" />
<asp:RequiredFieldValidator
runat="server"
id="vldfname"
ControlToValidate="frmfname"
ErrorMessage="First Name is required"
display="dynamic">
The fname field is Required!
</asp:RequiredFieldValidator></td>
	</tr>
	<tr>
		<td align="right">lname</td>
		<td> <asp:textbox id="frmlname" runat="server" />
<asp:RequiredFieldValidator
runat="server"
id="vldlname"
ControlToValidate="frmlname"
ErrorMessage="Last Name is required"
display="dynamic">
The lname field is Required!
</asp:RequiredFieldValidator></td>
	</tr>
	<tr>
		<td align="center"  colspan="2">
<asp:button id="button1" Text="Insert" onclick="doInsert" runat="server" />
<asp:Button id="button2" causesvalidation="false" Text="View Names" onclick="viewthem" runat="server" />
<asp:Button id="button3" Text="Clear" onclick="cleartextboxes" causesvalidation="false" runat="server" />
		</td>
	</tr>
</table>
<div align="center"><b><i><asp:Label ID="label1"  runat="server" /></i></b></div>

<hr>
<div align="center"><asp:Datagrid runat="server"
	Id="MyDataGrid"
	GridLines="Both"
	cellpadding="0"
	cellspacing="0"
	Headerstyle-BackColor="#8080C0"
	Headerstyle-Font-Name="Arial"
	Headerstyle-Font-Size="14"
	Headerstyle-Font-Bold="true"
	Width="50%"
	BackColor="#8080FF"
	Font-Name="Arial"
	Font-Size="11"
	BorderColor="Black"
	AllowPaging = "True"
	PageSize = "5"
	PagerStyle-Mode = "NumericPages"
	PagerStyle-PageButtonCount = "5"
	PagerStyle-HorizontalAlign="Center"
	OnPageIndexChanged = "Page_Change"
	visible="false">
</asp:DataGrid></div>
</Form>

</body>
</html>