Reading & Writing To a Text File

This sample uses an old Mother Goose Rhyme to demonstrate how to read a text file, and display it in a Multiline TextBox.

Then, when the user makes changes to the actual text, it can be saved, overwriting the original file, with the changes made.

(Please be nice with the changes you make – this is seen by thousands of people of all age groups)

<%@ Import Namespace="System.IO" %>
<script language="VB" Runat="server">
Dim FilePath as String = Server.MapPath("/wishes.txt")
Dim objFileWriter as StreamWriter
Dim objStreamReader as StreamReader
Dim sContents as String=""
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
	ReadFile()
end if
End Sub

Sub doSave(Source as Object, E as EventArgs)
	sContents = txtTextFile.text
	objFileWriter = File.CreateText(FilePath)
	objFileWriter.Write(sContents)
	objFileWriter.Close()
	ReadFile
	ph1.visible="True"
	label1.Text="Your Changes Have been made!"
End Sub

Sub ReadFile()
	objStreamReader = File.OpenText(FilePath)
	Dim contents as String = objStreamReader.ReadToEnd()
	txtTextFile.text = contents
	objStreamReader.Close()
End Sub
</script>
<asp:TextBox id="txtTextFile"
	Width="500"
	Rows="10"
	TextMode="MultiLine"
	Runat="server" /><br>
<asp:Button id="button1"
	Text="Save Changes"
	onclick="doSave"
	Runat="server" /><p>
<asp:placeholder ID="ph1" Visible="False" Runat="server">
<hr>
<asp:Label ID="label1" Runat="server" />
</asp:placeholder>

Email Column in a DataGrid

This sample shows how to use a TemplateColumn to combine fields from a database to display an email (mailto) link.

To do this, we use the FirstName, LastName, Email (and Title, Address and City) fields of the Northwind database.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<script language="VB" Runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
	Dim strConn as string = "server=YourServer;uid=YourUserID;" & _
		"pwd=YourPassword;database=Northwind"
	Dim MySQL as string = "Select * from Employees"
	Dim MyConn as New SQLConnection(strConn)
	Dim ds as DataSet=New DataSet()
	Dim Cmd as New SQLDataAdapter(MySQL,MyConn)
	Cmd.Fill(ds,"Employees")
	MyDataGrid.Datasource=ds.Tables("Employees").DefaultView
	MyDataGrid.DataBind()
End Sub
</script>

<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.1">
	<title>Email Column in a DataGrid</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:Datagrid Runat="server"
	Id="MyDataGrid"
	GridLines="Both"
	cellpadding="0"
	cellspacing="0"
	Headerstyle-BackColor="#BDCFE7"
	Headerstyle-Font-Name="Arial"
	Headerstyle-Font-Size="8"
	BackColor="#E7EFFF"
	Font-Name="Arial"
	Font-Size="8"
	BorderColor="Black"
	AutogenerateColumns="False">
	<Columns>
		<asp:TemplateColumn HeaderText="Email">
			<ItemTemplate>
			<a href=''mailto:<%# Container.DataItem("email") %>''>
				<%# Container.DataItem("FirstName") %>
				<%# Container.DataItem("LastName") %></a>
			</ItemTemplate>
		</asp:TemplateColumn>
		<asp:BoundColumn DataField="Title" HeaderText="Title"></asp:BoundColumn>
		<asp:BoundColumn DataField="Address" HeaderText="Address"></asp:BoundColumn>
		<asp:BoundColumn DataField="City" HeaderText="City"></asp:BoundColumn>
	</Columns>
</asp:DataGrid>
</form>
</body>
</html>

Displaying a Calculated Column in a DataGrid

Sometimes, it becomes necessary to create a ‘calculated column’ for display in a DataGrid. In this sample, we create a ‘Helper Function’ called ‘DoTotals’, in which we take the UnitsInStock field and multiply it by the UnitPrice field, to come up with a ‘Total Cost’ column. This sounds complicated, but once you see how it’s done, you’ll see that it’s quite a simple procedure.

We simply add a Template Column, and in DotNet CodeBlocks, we call the function called ‘DoTotals’. Then, we use DotNet formatting (String.Format(“{0:c}”, iPrice*IInstock) to format the output as Currency.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<script language="VB" Runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
BindData
End Sub

Function DoTotals(iPrice, iInstock) as String
DoTotals=String.Format("{0:c}", iPrice*IInstock)
End Function
Sub Page_Change(sender As Object, e As DataGridPageChangedEventArgs)
MyDataGrid.CurrentPageIndex = e.NewPageIndex
BindData
End Sub

Sub BindData()
Dim strConn as string = "server=(local);uid=YourUserID;pwd=YourPWD;database=Northwind"
Dim MySQL as string = "Select [ProductName], [UnitPrice], [UnitsInStock] from Products"
Dim MyConn as New SQLConnection(strConn)
Dim ds as DataSet=New DataSet()
Dim Cmd as New SQLDataAdapter(MySQL,MyConn)
Cmd.Fill(ds,"Products")
MyDataGrid.Datasource=ds.Tables("Products").DefaultView
MyDataGrid.DataBind()
End Sub
</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 3.1">
<title>Displaying a Calculated Column in a DataGrid</title>
</head>
<body>
<form id="form1" Runat="server">
<div align="center"><asp:Datagrid Runat="server"
Id="MyDataGrid"
GridLines="Both"
cellpadding="0"
cellspacing="0"
Headerstyle-BackColor="#BDCFE7"
Headerstyle-Font-Name="Arial"
Headerstyle-Font-Size="8"
BackColor="#E7EFFF"
Font-Name="Arial"
Font-Size="8"
BorderColor="Black"
AllowPaging = "True"
PageSize = "5"
PagerStyle-Mode = "NumericPages"
PagerStyle-HorizontalAlign="Center"
PagerStyle-PageButtonCount = "10"
OnPageIndexChanged = "Page_Change"
AutogenerateColumns="False">
<Columns>
<asp:BoundColumn DataField="ProductName"
HeaderStyle-Font-Bold="True"
HeaderText="ProductName">
</asp:BoundColumn>
<asp:BoundColumn DataField="UnitPrice"
HeaderStyle-Font-Bold="True"
HeaderText="Unit Price">
</asp:BoundColumn>
<asp:BoundColumn DataField="UnitsInStock"
HeaderStyle-Font-Bold="True"
HeaderText="Units In Stock">
</asp:BoundColumn>
<asp:TemplateColumn HeaderStyle-Font-Bold="True"
HeaderText="Total Cost"
ItemStyle-HorizontalAlign="Right">
<ItemTemplate>
<%# DoTotals(Container.DataItem("UnitPrice"), Container.DataItem("UnitsInStock"))%>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid></div>
</form>
</body>
</html>

Time Choice in ASP.NET Using DropDownLists

This sample shows how to combine the output from multiple DropDownLists in to 1 ‘Date/Time field’

<script language="VB" Runat="server">
Dim myDtTime as DateTime
Dim sDtTime as String
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
	LoadHours
	LoadMinutes
end if
End Sub

Sub LoadHours()
Dim x as Integer
	For x=1 to 12
		ddlHours.Items.Add(x)
	next x
End Sub

Sub LoadMinutes()
Dim x as Integer
	For x=10 to 50 Step 10
		ddlMinutes.Items.Add(x)
	next x
End Sub

Sub doTime(Source as Object, E as EventArgs)
	sDtTime=ddlHours.SelectedItem.Text & ":" & ddlMinutes.SelectedItem.Text  & " " & ddlTime.SelectedItem.Text
	myDtTime=sDtTime
	label1.text=myDtTime
End Sub

</script>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.1">
	<title>Time Choice Using DropDownLists</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:DropDownList id="ddlhours" Runat="server"/>
<asp:DropDownList id="ddlMinutes" Runat="server"/>
<asp:DropDownList id="ddlTime" Runat="server">
<asp:ListItem>AM</asp:ListItem>
<asp:ListItem>PM</asp:ListItem>
</asp:DropDownList>
<asp:Button id="button1" Text="Get Time" onclick="doTime" Runat="server" />

<asp:Label ID="label1" Runat="server" />
</form>
</body>
</html>

Using Arrays, Split and a DropDownList

Here is a way to use the string method “Split” to add items to an Array, manipulate them a little further, and add the data to a DropDownList, as the value and text properties.

<script language="VB" Runat="server">
Dim StateStr as String ="AL,Alabama|AK,Alaska|AZ,Arizona|AR,Arkansas|CA,California|CO,Colorado"

Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
	Dim StateArray As Array
	StateArray =StateStr.Split("|")

	Dim i As Integer
	For i = 0 To UBound(StateArray)
		Dim sColArray as Array
		sColArray=StateArray(i).Split(",")   ' older way:  sColArray=Split(StateArray(i),",")
		Dim li as New ListItem
		Dim liItem as ListItem=New ListItem(sColArray(1), sColArray(0))
		Trace.Warn ("i = " & i)
		ddl.Items.Insert(i,liItem)
	Next
end if
End Sub

Sub doGetState(Source as Object, E as EventArgs)
lblState.text="State = " & ddl.SelectedItem.Text & _
	"<br>Abbr = " & ddl.SelectedItem.Value
End Sub

</script>

<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.1">
	<title>Using Array, String.Split and a DropDownList</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:DropDownList id="ddl" Runat="server">
</asp:DropDownList>

<asp:Button id="button1"
	Text="Get State"
	onclick="doGetState"
	Runat="server" /><p>

<asp:Label ID="lblState" Runat="server" />
</form>
</body>
</html>

Changing Calendar Dates w/DropDownLists

This sample shows how to use other samples of populating DropDownlists (with Months and Years), and then change the Month and Date of the Calendar Server Control, built into ASP.Net

<script language="VB" Runat="server">
Dim MyDate as DateTime
Dim intMnth as Integer
Dim x as Integer
Dim myYear as Integer

Sub Page_Load(Source as Object, E as EventArgs)
MyDate=DateTime.Now()
myYear=MyDate.Year
if not Page.IsPostBack then
For x = 1 To 12
ddlMonths.Items.Add(New ListItem(MonthName(x), x))
Next
ddlYears.Items.Add(myYear)
For x=1 to 5
ddlYears.Items.add(new ListItem(myYear+x))
next
intMnth = Month(Now)
ddlMonths.selectedIndex=intMnth-1
end if
End Sub

Sub ChangeYear(Source as Object, E as EventArgs)
Dim sNewDate as String
sNewDate =CInt(ddlMonths.SelectedItem.Value) & "/1/" & ddlYears.SelectedItem.text
Calendar1.TodaysDate=sNewDate
End Sub

Sub CleanYear(Source as Object, E as EventArgs)
Calendar1.TodaysDate=MyDate
End Sub
</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 3.1">
<title>Changing Calendar Dates w/DropDownLists</title>
</head>
<body>
<form id="form1" Runat="server">
<div align="center">
<table border="0" width="50%">
<tr>
<td align="Center" valign="Top" Colspan="2">
<font Size="2"><b>Choose Date</b></font></td>
</tr>
<tr>
<td align="Right" width="50%" valign="Top">Month:
<asp:DropDownList id="ddlMonths" Font-Size="8pt"
Runat="server">
</asp:DropDownList>&nbsp;</td>
<td align="Left" width="50%" valign="Top">Year:
<asp:DropDownList id="ddlYears"
Runat="server" Font-Size="8pt">
</asp:DropDownList> </td>
</tr>
<tr>
<td align="Center" valign="Top" Colspan="2">
<asp:LinkButton id="btnChange"
Text="Change Date"
Font-Size="9pt" onclick="ChangeYear" Runat="server" />
&nbsp; | &nbsp; <asp:LinkButton id="btnReset"
Text="Reset Date" onclick="cleanYear"
Font-Size="9pt" Runat="server" />
</td>
</tr>
<tr>
<td align="Center" valign="Top" Colspan="4">
<asp:Calendar id="Calendar1" Runat="server"
Backcolor="White" Forecolor="Black"
Borderwidth="2" ShowGridLines="true" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

Giving all Textboxes One Javascript Function

The main scenario of this code sample is that we have a form with multiple textboxes and we want to add ONE Javascript attribute (onChange) to ALL of them, so that when the textboxes lose focus, the text inside them become ALL CAPITAL LETTERS.

There are two sections needed to accomplish this. One is the actual Javascript Function itself, which we call ‘convcaps’. The second section shows how to add the attribute to each and every textbox on the page. Normally, we would just add a line for each textbox to add the onChange attribute to each one, but what if you had many textboxes on the page? That would get cumbersome, so during page load, we show you how to iterate though all the controls, finding only textboxes and applying the attribute to each and every one.

<%@ Page Language="VB"  %>
<script language="VB" Runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
	If Not Page.IsPostBack Then
		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).Attributes.Add("onChange", "convcaps(" + ctl.ID + ");")
				Trace.Warn ("ctl.ID = " & ctl.ID & " - " & ctl.GetType().ToString())
			End If
		Next ctl
	End If
End Sub
</script>

<script type="text/javascript">
function convcaps(myVar)
{
myVar.value=myVar.value.toUpperCase();
}

// - End of JavaScript - -->
</script>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.1">
	<title>Giving all Textboxes One Javascript Function</title>
</head>
<body>
<form id="form1" Runat="server">
	<table>
			<tr>
				<td align="Left" valign="Top">
					<asp:TextBox id="textbox1" Runat="server" />
				</td>
				<td align="Left" valign="Top">
					<asp:TextBox id="textbox2" Runat="server" />
				</td>
			</tr>
			<tr>
				<td align="Left" valign="Top">
					<asp:TextBox id="textbox3" Runat="server" />
				</td>
				<td align="Left" valign="Top">
					<asp:TextBox id="textbox4" Runat="server" />
				</td>
			</tr>
		</table>
</form>
</body>
</html>

Master-Detail with DropDownList

This sample shows how to populate a DropDownList from a Database, and then, displaying the entire record details, based on the DropDownList choice which was made. We are using the OleDb Data Provider, in this case, using the MS Access database, Northwind.

There are two ways shown here, on how to display the details. The first way is merely by populating a DataGrid. This is just the ‘down and dirty’ method of choosing and displaying.

The second method requires getting your hands ‘dirty’ somewhat (sorry for all the ‘dirt’ references), by assigning the variables when the DataReader is being read, and then manually creating the form in which the data is displayed.

Also, you will notice that there is a ‘Helper Function’called ‘FixDR’ which guards against Null data in the database. Without this function, an error would be raised when trying to create a variable from null data.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDB" %>
<script language="VB" Runat="server">
Dim strConn as string = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
		server.mappath("\data\northwind.mdb") & ";"
Dim sEmployeeID, sLastName, sFirstName, sTitle, sTitleOfCourtesy, sBirthDate, sHireDate as String
Dim sAddress, sCity, sRegion, sPostalCode, sCountry, sHomePhone, sExt as String
Sub Page_Load(Source as Object, E as EventArgs)
	if not Page.IsPostBack then
		Dim MySQL as string = "Select [LastName] from Employees"
		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)
		ddlEmp.DataSource = objDR
		ddlEmp.DataTextField="LastName"

		ddlEmp.DataBind()
		MyConn.Close()
		ddlEmp.items.insert(0,"")
	end if
End Sub
Sub doGrid()
	if ddlEmp.SelectedItem.Text <>"" then
		Dim MySQL as string = "Select EmployeeID, LastName, FirstName, Title, TitleofCourtesy, " & _
		"BirthDate, HireDate, Address, City, Region, PostalCode, Country, HomePhone, Extension " & _
		"from Employees where LastName = ''" & _
		ddlEmp.SelectedItem.Text & "''"
		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)
		empGrid.DataSource = objDR
		empGrid.DataBind
		MyConn.Close
	End If
End Sub

Sub doRest(Source as Object, E as EventArgs)
	ph1.visible="True"
	Dim MySQL as string = "Select * from Employees where LastName = ''" & _
	ddlEmp.SelectedItem.Text & "''"
	if ddlEmp.SelectedItem.Text <>"" then
		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)
		While objDR.Read
			sEmployeeID = FixDR(objDR("EmployeeID"))
			sLastName = FixDR(objDR("LastName"))
			sFirstName = FixDR(objDR("FirstName"))
			sTitle = FixDR(objDR("Title"))
			sTitleOfCourtesy = FixDR(objDR("TitleOfCourtesy"))
			sBirthDate = FixDR(objDR("BirthDate"))
			sHireDate = FixDR(objDR("HireDate"))
			sCity = FixDR(objDR("City"))
			sRegion = FixDR(objDR("Region"))
			sPostalCode = FixDR(objDR("PostalCode"))
			sCountry = FixDR(objDR("Country"))
			sHomePhone = FixDR(objDR("HomePhone"))
			sExt = FixDR(objDR("Extension"))
		End While
		Page.DataBind()
	End If
	doGrid
End Sub

Function FixDR(sItem) as String
	if Not sItem is System.DBNull.Value then FixDR=sItem
End Function
</script>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.1">
	<title>Master-Detail with DropDownList</title>
</head>
<body>
<form id="form1" Runat="server">
Choose a Last Name from the list:
<asp:DropDownList id="ddlEmp"
	AutoPostBack="True"
	OnSelectedIndexChanged="doRest"
	Runat="server"/><br>
<asp:Datagrid Runat="server"
	Id="EmpGrid"
	GridLines="Both"
	cellpadding="0"
	cellspacing="0"
	Headerstyle-BackColor="#8080FF"
	Headerstyle-Font-Name="Arial"
	Headerstyle-Font-Size="8"
	BackColor="#C8E1FB"
	Font-Name="Arial"
	Font-Size="8"
	BorderColor="Black">
</asp:DataGrid>
<asp:placeholder ID="ph1" Visible="False" Runat="server">
	<b>Emp ID:</b> <%# sEmployeeID %><br>
	<b>LastName:</b> <%# sLastName %><br>
	<b>FirstName:</b> <%# sFirstName %><br>
	<b>Title: </b><%# sTitle %><br>
	<b>Title of Courtesy:</b> <%# sTitleOfCourtesy %><br>
	<b>BirthDate: </b><%# sBirthDate %><br>
	<b>HireDate: </b><%# sHireDate %><br>
	<b>Address: </b><%# sAddress %><br>
	<b>City:</b> <%# sCity %><br>
	<b>Region: </b><%# sRegion %><br>
	<b>Postal Code:</b> <%# sPostalCode %><br>
	<b>Country:</b> <%# sCountry %><br>
	<b>Home Phone: </b><%# sHomePhone %><br>
	<b>Extension:</b> <%# sExt %>
</asp:placeholder>
</form>
</body>
</html>

Demo of the Replace Function (String Class)

With multiline textboxes, it’s very easy to enter data using line breaks, with the Enter key. However, when displaying that information (whether or not it’s stored in a database), the line breaks are in a format that a Web Browser cannot translate.

Therefore, it’s necessary to replace the embedded line breaks which were entered, with HTML line breaks, when displaying the information back in the Browser. This sample shows how to use the String Class’s ‘Replace’ method to do it.

<script language="VB" Runat="server">
Dim sResults as String
Sub ShowText(Source as Object, E as EventArgs)
	lblResults.text=txtStuff.text
End Sub

Sub ShowExact(Source as Object, E as EventArgs)
	sResults=txtStuff.Text
	'Make text 'web-ready', by replacing embedded
	'line breaks with HTML line breaks:
	sResults=sResults.Replace(vbcrlf, "<br>")
	lblResults.text=sResults
End Sub
</script>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.1">
	<title>Untitled</title>
</head>
<body>
<form id="form1" Runat="server">
Type text in the box below, using the <i>Enter</i> key to insert line breaks:</font>
<asp:TextBox id="txtStuff"
	Columns="60"
	Rows="10"
	TextMode="MultiLine"
	Runat="server" /><br>
<asp:Button id="button1" Text="Show Pure
	Text" onclick="ShowText"
	Runat="server" />
<asp:Button id="button2" Text="Show Results as Typed"
	onclick="ShowExact"
	Runat="server" />
<p>
<asp:Label ID="lblResults" Runat="server" />
</form>
</body>
</html>

Conditional Javascript – - Alert Box within If/Then Block

Sometimes, in ASP.Net, we might want a message box to pop up with a particular message, based on a choice the user makes. In ASP.Net, since it’s a server-side language, it can not natively create a message box on the client side.

This can be done, however, with the Javascript alert box. One scenario (which is demonstrated here) would be to check for a user in the database, when the user logs in. This sample won’t go into the details of the database interaction, since there are several examples on this site which will show that part. Here, we are just using Radio Buttons to emulate whether or not the user is found or not found in the database.

<script language="VB" Runat="server">
Dim blNotExist as Boolean
Sub doCheck(Source as Object, E as EventArgs)
	if rbNot.Checked="True" then
		blNotExist="True"
	else
		blNotExist="False"
	End If

	if blnotExist="true" then
		Response.Write ("<" & "script>alert(''User does not exist'');<" & "/script>")
	else
		Response.Write ("<" & "script>alert(''User does exist'');<" & "/script>")
	End If
End Sub

</script>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.1">
	<title>Conditional Javascript - - Alert Box within If/Then Block</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:RadioButton Text="Does Not Exist"
	id="rbNot"
	GroupName="Exist" Runat="server" />
<asp:RadioButton Text="Does Exist"
	id="rbDoes"
	GroupName="Exist" Runat="server" />
<asp:Button id="button1" Text="Check User" onclick="doCheck" Runat="server" />
</form>
</body>
</html>