Reading an HTML Text File

This sample shows how to use the StreamReader class to read an HTML text file, line by line, and display it on your page. Notice how the vbcrlfs (VB Line Feed/Carriage Return), in the contents of the file are replaced with HTML Line Breaks (
). That’s because an HTML page will not recognize a vbcrlf – but the HTML equivalent is the HTML line break, so we make the replacement.

This method has many uses, including the possibility of including an HTML file in an email.

Happy coding!”

<%@ Import Namespace="System.IO" %>
<script language="VB" Runat="server">
Dim FilePath as String
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
FilePath=Server.MapPath("/wishes.htm")
	ReadFile()
end if
End Sub

Sub ReadFile()
	objStreamReader = File.OpenText(FilePath)
	Dim contents as String = objStreamReader.ReadToEnd()
	lbltextFile.text = contents.Replace(vbcrlf, "<br>")
	objStreamReader.Close()
End Sub
</script>
<html>
	<head>
		<meta name="GENERATOR" Content="ASP Express 4.0">
		<title>Reading an HTML File</title>
	<STYLE TYPE="text/css">
<!--
BODY {
	font-family : Verdana;
	font-size : 11pt;
}
-->
</STYLE>
</head>
	<body>
		<form id="form1" Runat="server">
			<asp:Label id="lblTextFile" Runat="server" /><br>
				<p>
				<asp:placeholder ID="ph1" Visible="False" Runat="server">
				<hr>
				<asp:Label ID="label1" Runat="server" />
			</asp:placeholder>
		</form>
	</body>
</html>

Retrieving the Full DB Schema – SQL Server

This code sample simply shows how to retrieve the full schema of a SQL Server table. For this sample, we’re using the Northwind database – the Employees table. Be sure to set the connection string on your machine, so that it is correct for the DB you are accessing.

<%@ 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=YourUID;pwd=YourPWD;database=Northwind"
Dim MySQL as string = "Select * from Employees"
Dim MyConn as New SQLConnection(strConn)
Dim schemaTable As DataTable
Dim myField As DataRow
Dim myProperty As DataColumn
Dim Cmd as New SQLCommand(MySQL, MyConn)
MyConn.Open()
Dim dr As SQLDataReader
dr = cmd.ExecuteReader
schemaTable = dr.GetSchemaTable()
For Each myField In schemaTable.Rows
For Each myProperty In schemaTable.Columns
label1.text+="<b>" & MyProperty.ColumnName & " = </b>" & myField(myProperty).ToString() & "<br>"
Next
label1.text+="<p>"
Next
dr.Close()
MyConn.Close()
End Sub
</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 4.0">
<title>Getting Column Names from a SQL Server Table</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:Label ID="label1" Runat="server" />
</form>
</body>
</html>

Retrieving the Full DB Schema – OleDB

This code sample simply shows how to retrieve the full schema of an MS Access table. For this sample, we’re using the Northwind database – the Employees table. Be sure to set the connection string path on your machine, so that it is correct for the DB you are accessing.

<%@ 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\northwind.mdb") & ";"
		Dim MySQL as string = "Select * from Employees"
		Dim MyConn as New OleDBConnection(strConn)
		Dim schemaTable As DataTable
		Dim myField As DataRow
		Dim myProperty As DataColumn
		Dim Cmd as New OLEDBCommand(MySQL, MyConn)
		MyConn.Open()
		Dim dr As OleDbDataReader
		dr = cmd.ExecuteReader
		schemaTable = dr.GetSchemaTable()
		For Each myField In schemaTable.Rows
			For Each myProperty In schemaTable.Columns
					label1.text+="<b>" & myProperty.ColumnName & "</b> = " & myField(myProperty).ToString() & "<br>"
		     Next
		     label1.text+="<p>"
		Next
		dr.Close()
		MyConn.Close()
	End Sub
</script>
<html>
	<head>
		<meta name="GENERATOR" Content="ASP Express 4.0">
		<title>Getting Column Names from MS Access Table</title>
	</head>
	<body>
		<form id="form1" Runat="server">
			<asp:Label ID="label1" Runat="server" />
			<asp:DropDownList id="ddl" Runat="server">
			</asp:DropDownList>
		</form>
	</body>
</html>

Getting Column Names – OleDb/MS Access

Sometimes we find it necessary to retrieve the names of the columns of a particular table in an OleDb (MS Access, for this example).

This sample shows how to get those names and add them to a DropDownList. Be sure to change the connection string, so that it matches the path to your MS Access database

<%@ 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\northwind.mdb") & ";"
Dim MySQL as string = "Select * from Employees"
Dim MyConn as New OleDBConnection(strConn)
Dim schemaTable As DataTable
Dim myField As DataRow
Dim myProperty As DataColumn
Dim Cmd as New OLEDBCommand(MySQL, MyConn)
MyConn.Open()
Dim dr As OleDbDataReader
dr = cmd.ExecuteReader
schemaTable = dr.GetSchemaTable()
For Each myField In schemaTable.Rows
For Each myProperty In schemaTable.Columns
if myProperty.ColumnName="ColumnName" then
ddl.Items.add(myField(myProperty).ToString())
End If
Next
Next
dr.Close()
MyConn.Close()
End Sub
</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 4.0">
<title>Getting Column Names from MS Access Table</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:Label ID="label1" Runat="server" />
<asp:DropDownList id="ddl" Runat="server">
</asp:DropDownList>
</form>
</body>
</html>

Working with Calender Day of Week

This sample shows how to get the Day of Week when clicking a particular calendar date, as well as manipulating the display of the calendar based on the day of the week

<script language="VB" Runat="server">
	Sub Page_Load(Source as Object, E as EventArgs)

	End Sub
Sub Calendar_DayRender(source As Object, e As DayRenderEventArgs)
             Dim d as CalendarDay
            d = e.Day
If e.Day.IsWeekend Then
	if d.Date.DayofWeek.ToString="Sunday" then
 		e.Cell.BackColor = System.Drawing.Color.Green
 	else
 		e.Cell.BackColor = System.Drawing.Color.Red
 	End If
e.Cell.ForeColor = System.Drawing.Color.White
End If
End Sub

Sub GetDate(Source as Object, E as EventArgs)
	label1.text=cal1.SelectedDate.DayofWeek.ToString
End Sub
</script>
<html>
	<head>
		<meta name="GENERATOR" Content="ASP Express 4.0">
		<title>Untitled</title>
	</head>
	<body>
		<form id="form1" Runat="server">
			<asp:Calendar id="cal1" Runat="server"
				 WeekendDayStyle-Font-Bold="True"
				ondayrender="Calendar_DayRender"
				 Font-Name="Arial"
			OnSelectionChanged="GetDate" Backcolor="White" Forecolor="Black"
				Borderwidth="2" ShowGridLines="true" />
			<asp:Label ID="label1" Runat="server" />
		</form>
	</body>
</html>

Holidays with the Calendar Control

Adding preset Holidays to the displayed ASP.Net Calendar Control is really very simple. First, we need to creat a DayRender Event, which we call ‘Cal1_DayRender’, for this example. Then, we need to point to that DayRender Event, in the Control Tag itself (OnDayRender=”Cal1_DayRender”).

Then, we need to create an array (globally) with the max number of months and the max number of days possible:

Dim holidays(12, 31) As String

Then, inside the Page_Load Event, we just list the holidays we wish to have displayed automatically, using the month and the date. That’s all there is to it!

As an extra here, we can also see how to programmatically change the font and font size of a label, in the Cal1_DayRender Event.

<script language="VB" Runat="server">
Dim holidays(12, 31) As String
	Sub Page_Load(Source as Object, E as EventArgs)
	  	holidays(8, 5) = "Birthday"
	 	holidays(8, 14) = "Anniversary"
		holidays(1,1)   = "New Year''s Day"
		holidays(7,4)="The US Declares Independance"
		holidays(12,25)="Christmas"
		holidays(12,31)="New Year''s Eve"
	End Sub
Sub Cal1_DayRender(sender As Object, _
   e As DayRenderEventArgs)
   If e.Day.IsOtherMonth Then
      e.Cell.Controls.Clear()
   Else
      Dim aDate As Date = e.Day.Date
      Dim aHoliday As String = holidays(aDate.Month, aDate.Day)
      If (Not aHoliday Is Nothing) Then
         Dim aLabel As Label = New Label()
		aLabel.Font.Name = "verdana"
 		aLabel.Font.Size = FontUnit.Point(10)
		aLabel.Text = "<br>" & aHoliday
		e.Cell.Controls.Add(aLabel)
      End If
   End If
End Sub
</script>
<html>
	<head>
		<meta name="GENERATOR" Content="ASP Express 4.0">
		<title>Holidays in the ASP.Net Calendar</title>
	</head>
	<body><asp:Label ID="PutIDNameHere"   Runat="server" />
		<form id="form1" Runat="server">
			<asp:Calendar runat="server"
				id="cal1"
				Backcolor="White"
				Forecolor="Black"
				Borderwidth="2"
				Width="75%"
				ShowGridLines="true"
				OnDayRender="Cal1_DayRender"
				SelectedDayStyle-Backcolor="#DEEFFF"
				SelectedDayStyle-forecolor="Black"
				TitleStyle-BackColor="#DEEFFF"
				TitleStyle-Font-Bold="True"
				TitleStyle-Height="36px"
				OtherMonthDayStyle-ForeColor="gray"
				TodayDayStyle-Font-Bold="True"
				TodayDayStyle-Font-Italic="True"
				TodayDayStyle-Font-Size="12pt"
				DayHeaderStyle-Font-Bold="True"
				DayHeaderStyle-BackColor="LightGray" />
		</form>
	</body>
</html>

Using MySQL with ASP.Net

MySQL is a very robust Database server, which works similarly to SQL Server, in that it’s a DataBase server, unlike MS Access. For this sample, we merely imported several of the tables from the Northwind database, to keep it as simple as possible.

In order to make a step up from MS Access, and learn the structure and use of a DataBase server, along with the fact that there is no added expense (MYSQL is free), here, we show how simple, coding-wise, it is, to make the transition.

There is a somewhat more detailed tutorial on the use of MySQL here:
http://aspnet101.com/aspnet101/tutorials.aspx?id=39

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.ODBC" %>
<script language="VB" Runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
BindData
End Sub
Sub BindData()
Dim strConn as string
strConn = "DRIVER={MySQL};SERVER=IP_Address;DATABASE=YourDB;" & _
"USER=YourUID;PASSWORD=YourPWD; OPTION=3;"
Dim MySQL as string = "Select CustomerID, CompanyName, ContactTitle, " & _
"Address, City, Phone from Customers"
Dim MyConn as New ODBCConnection(strConn)
Dim ds as DataSet=New DataSet()
Dim Cmd as New ODBCDataAdapter(MySQL,MyConn)
Cmd.Fill(ds,"Customers")
MyDataGrid.Datasource=ds.Tables("Customers").DefaultView
MyDataGrid.DataBind()
End Sub

Sub Page_Change(sender As Object, e As DataGridPageChangedEventArgs)
MyDataGrid.CurrentPageIndex = e.NewPageIndex
BindData
End Sub
</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 4.0">
<title>MySQL with ASP.Net</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="12"
BackColor="#E7EFFF"
Font-Name="Arial"
Font-Size="10"
AlternatingItemStyle-BackColor="#E7EFFF"
AlternatingItemStyle-Font-Name="Arial"
AlternatingItemStyle-Font-Size="10"
BorderColor="Black"
AllowPaging = "True"
PageSize = "10"
PagerStyle-Mode = "NumericPages"
PagerStyle-HorizontalAlign="Center"
PagerStyle-PageButtonCount = "10"
OnPageIndexChanged = "Page_Change">
</asp:DataGrid>
</form>
</body>
</html>

Inserting Data With Different Server Controls

Everyone has used textboxes in forms to insert data into a database. However, many people have asked me how to insert data with different types of server controls. Therefore, this insert code sample shows how to use TextBoxes, a DropDownList and a RadioButtonList as input controls.

Notice, that, the same syntax can be used for any of the other List-type controls, also (Listbox, CheckboxList)

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<script language="VB" Runat="server">
Dim strConn as string = "server=YourServer;uid=YourUID;pwd=YourPWD;database=Your_DB"
Sub doInsert(Source as Object, E as EventArgs)
Dim MySQL as string = "Insert into TestInsert (fname, lname, sex, position) Values(@fname, @lname, @sex, @position)"

Dim MyConn as New SQLConnection(strConn)
Dim Cmd as New SQLCommand(MySQL, MyConn)
cmd.Parameters.Add(New SQLParameter("@fname", txtFname.text))
cmd.Parameters.Add(New SQLParameter("@lname", txtlname.text))
cmd.Parameters.Add(New SQLParameter("@sex", rblSex.SelectedItem.text))
cmd.Parameters.Add(New SQLParameter("@position", ddlPosition.SelectedItem.text))
MyConn.Open()
Cmd.ExecuteNonQuery()
MyConn.Close()
label1.text = "Your entry was successful!"
getEntries
End Sub

Sub getEntries()
Dim MySQL as string = "Select * from testInsert"
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()
MyConn.Close()

End Sub
</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 3.5">
<title>Inserting Data With Different Server Controls</title>
</head>
<body>
<form id="form1" Runat="server">
First Name: <asp:TextBox id="txtFname" Runat="server" /><br>
Last Name: <asp:TextBox id="txtLname" Runat="server" /><br>
Sex: <asp:RadioButtonList id="rblSex" RepeatDirection="Horizontal" Runat="server">
<asp:ListItem>Male</asp:ListItem>
<asp:ListItem>Female</asp:ListItem>

</asp:RadioButtonList> Position : <br> <asp:DropDownList id="ddlPosition" Runat="server">
<asp:ListItem>Manager</asp:ListItem>
<asp:ListItem>Non-Manager</asp:ListItem>
</asp:DropDownList><br>
<asp:Button id="button1" Text="Insert" onclick="doInsert" Runat="server" />
<br> <asp:Label ID="label1" Runat="server" />
<br>
<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">
</asp:DataGrid>
</form>
</body>
</html>

Switch Between Editable and Read-Only

In the course of programming with forms, occasionally, the user will need a choice as to whether the texboxes are actually editable or readonly. Let’s say, a checkbox, if checked will include a section of data, or Not include it (in the update/save process). In order to make it look like it’s editable or NOT editable, it’s possible to make changes to the appearance of the checkboxes.

This sample shows one method of doing just that. In this scenario, the background of the web page would be something other than the regular ‘white’, to help differentiate between the two settings.

<script language="VB" Runat="server">
Sub MakeReadOnly(sItem as TextBox)
sItem.borderwidth=unit.point(0)
sItem.Backcolor=System.Drawing.Color.FromARGB(&H78FFFAF0)
sItem.BorderStyle=BorderStyle.None
sItem.ReadOnly="True"
End Sub

Sub MakeEditable(sItem as TextBox)
sItem.borderwidth=unit.point(1)
sItem.Backcolor=System.Drawing.Color.White
sItem.BorderStyle=BorderStyle.Solid
sItem.ReadOnly="False"
End Sub

Sub doChanged(Source as Object, E as EventArgs)
if chkEdit.Checked ="True" then
MakeReadOnly(txtFname)
MakeReadOnly(txtLname)
chkEdit.Text="Make Editable"
else
MakeEditable(txtFname)
MakeEditable(txtLname)
chkEdit.Text="Make Read-Only/Non-Editable"
End If
End Sub
</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 3.2">
<title>Switch Between Editable and Read-Only</title>
</head>
<body>
<form id="form1" Runat="server">
<div style="background:#FFFAF0" style="BORDER-RIGHT: #000000 1px solid;
BORDER-LEFT:#000000 1px solid; BORDER-TOP:#000000 1px solid;
BORDER-BOTTOM:#000000 1px solid">
&nbsp;<br>
&nbsp; First Name: <asp:TextBox id="txtFname"
Bordercolor="black"
BorderWidth="1"
Text="Tom"
Runat="server" /><br>
&nbsp; Last Name: <asp:TextBox id="txtLName"
Bordercolor="black"
BorderWidth="1"
Text="Landry"
Runat="server" /><p>
<asp:Checkbox Text="Make Read-Only/Non-Editable"
id="chkEdit"
AutoPostBack="true"
OnCheckedChanged="doChanged"
Runat="server" /><br>&nbsp;

</div>
</form>
</body>
</html>

Javascript – Select-All with a Button and a TextBox

This code sample simply shows how to add an attribute to a button, in order to, when the button is clicked, select all the text from a particular textbox.

<script language="VB" Runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
txtMain.text="Four score and seven years ago, our forefathers brought forth " & _
"upon this continent, a new nation, conceived in liberty and dedicated to the " & _
"proposition that all men were created equal. <p>Now we are engaged in a great civil war, " & _
"testing whether that nation or any nation so conceived and so dedicated can long endure. "& _
"We are met on a great battlefield of that war. We have come to dedicate a portion of it " & _
"as a final resting place for those who died here that the nation might live. This we may, " & _
"in all propriety do. But in a larger sense, we cannot dedicate, we cannot consecrate, " & _
"we cannot hallow this ground. The brave men, living and dead who struggled here have " & _
"hallowed it far above our poor power to add or detract. The world will little note nor long " & _
"remember what we say here, but it can never forget what they did here. <p>" & _
"It is rather for us the living, we here be dedicated to the great task remaining before us--" & _
"that from these honored dead we take increased devotion to that cause for which they " & _
"here gave the last full measure of devotion--that we here highly resolve that these " & _
"dead shall not have died in vain, that this nation shall have a new birth of freedom, " & _
"and that government of the people, by the people, for the people shall not perish from the earth."
if not Page.IsPostBack then
myButton.attributes("onclick")="javascript:this.form.txtMain.focus();this.form.txtMain.select(); return false;"
end if
End Sub

</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 3.5">
<title>Javascript - Select-All with a Button and a TextBox</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:TextBox id="txtMain" TextMode="MultiLine" Rows="5" Width="450" Runat="server" /><br>
<asp:Button id="myButton" Text="Select All" Runat="Server"/>
</form>
</body>
</html>