Checking Existing Data Before Insert

Naturally, in many, if not most cases, the best scenario, before inserting new data, is to check to see if it’s already there, in order to keep from double-entering information.

In this sample we use a SQL Server table with 4 fields (id, title, link, and Description). The id field is an identity field, for auto-numbering purposes. That field will not need to be checked, of course. In this example, we will just be checking the title and link fields. Naturally, you can check more, depending on your circumstances.

The subroutine ‘SeeRecords’ is not necessary, but is here merely to show you the last record inserted (with your data).

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<script language="VB" Runat="server">
Dim blHasRows as Boolean
Sub doInsert(Source as Object, E as EventArgs)
Dim strConn as string = "server=YourServer;uid=YourUID;pwd=YourPWD;database=YourDB"
Dim MySQL as string = "Select * from samples where title=@title and link=@link"
Dim MyConn as New SQLConnection(strConn)
Dim objDR as SQLDataReader
Dim Cmd as New SQLCommand(MySQL, MyConn)
With Cmd.Parameters
.Add(New SQLParameter("@title", frmtitle.text))
.Add(New SQLParameter("@link", frmlink.text))
End With
MyConn.Open()
objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
if objDR.HasRows then
blHasRows="True"
else
blHasRows="False"
End If
MyConn.Close()
MySQL = "Insert into samples (title, link, Description) Values (@title, @link, @Description)"
Dim Cmd2 as New SQLCommand(MySQL, MyConn)
With Cmd2.Parameters
.Add(New SQLParameter("@title", frmtitle.text))
.Add(New SQLParameter("@link", frmlink.text))
.Add(New SQLParameter("@Description", frmDescription.text))
End With
if blHasRows="False" then
MyConn.Open()
cmd2.ExecuteNonQuery()
lblResults.text="Your information has been received!"
MyConn.Close
seeRecords()
else
lblResults.text="Sorry, that information is already in the database"
End If
End Sub

Sub Page_Load(Source as Object, E as EventArgs)

End Sub

Sub seeRecords()
Dim strConn as string = "server=YourServer;uid=YourUID;pwd=YourPWD;database=YourDB"
Dim MySQL as string = "Select Top 1 * from samples order by ID desc"
Dim MyConn as New SQLConnection(strConn)
Dim objDR as SQLDataReader
Dim Cmd as New SQLCommand(MySQL, MyConn)
With Cmd.Parameters
.Add(New SQLParameter("@title", frmtitle.text))
.Add(New SQLParameter("@link", frmlink.text))
End With
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.2">
<title>Checking Data before Inserting New Data</title>
</head>
<body>
<form id="form1" Runat="server">
<div align="center"><table>
<tr>
<td align="right">Title</td>
<td> <asp:textbox id="frmtitle" Text="Tender Moments" Runat="server" /></td>
</tr>
<tr>
<td align="right">Link</td>
<td> <asp:textbox id="frmlink" Text="http://tendermoments.com" Runat="server" /></td>
</tr>
<tr>
<td align="right">Description</td>
<td> <asp:textbox id="frmDescription" 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="lblResults" Font-Bold="True" 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">
</asp:DataGrid>
</div>
</form>
</body>
</html>

Searching, a DataSet, Paging & Parameters (MS Access)

Most of the examples on this site use a DataReader when demonstrating parameterized queries (Parameterized Queries Tutorial). However, it’s a little different, using a DataSet with a Select query, using parameterized queries.

In this sample, we use the Customers and Orders Table in the Northwind database.
We create both a DataAdapter and a Command object, along with the DataSet, to accomplish this. Naturally, to implement Paging in a DataGrid, we must have a DataSet. First, inside the Page_Load event, and also inside an if/Then/Postback block, we populate a DropDownList with the Items on which we will base the search. Then, in the BindData subroutine, we use the Selected Item from the DropDownList to search and populate the DataSet, which gets bound to the DataGrid and implements Paging.

Also notice, that we have an extra Sub called ‘GridOne’. Here, whenever the DropDownList item is changed, we assume the user is doing a new search. Therefore, we automatically set the CurrentPageIndex of the DataGrid to 0. This way, there aren’t any errors if the current page is higher than the page count in the new search.

Click here for the SQL Server sample of this code.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<script language="VB" Runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
Dim strConn as string = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
server.mappath("Northwind.mdb") & ";"
Dim MySQL as string = "Select [CustomerID], [CompanyName] from Customers"
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)
ddlCustomer.DataSource = objDR
ddlCustomer.DataValueField="CustomerID"
ddlCustomer.DataTextField="CompanyName"
ddlCustomer.DataBind()
MyConn.Close()
end if
End Sub

Sub Page_Change(sender As Object, e As DataGridPageChangedEventArgs)
MyDataGrid.CurrentPageIndex = e.NewPageIndex
BindData
End Sub
Sub BindData()
Dim strConn as string = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
server.mappath("Northwind.mdb") & ";"
Dim MySQL as string = "Select * from Orders Where CustomerID = @CustID Order by OrderID "
Dim MyConn as New OleDbConnection(strConn)
Dim ds as DataSet=New DataSet()
Dim da as OleDbDataAdapter=New OleDbDataAdapter
Dim Cmd as New OleDbCommand    (MySQL,MyConn)
da.SelectCommand = cmd
cmd.Parameters.Add(New OleDbParameter("@CustID", ddlcustomer.SelectedItem.Value))
da.Fill(ds,"Orders")
MyDataGrid.Datasource=ds.Tables("Orders").DefaultView
MyDataGrid.DataBind()
End Sub

Sub GetData(Source as Object, E as EventArgs)
BindData
End Sub

Sub GridOne(Source as Object, E as EventArgs)
MyDataGrid.currentpageindex=0
End Sub

</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 3.2">
<title>Searching, a DataSet, Paging &amp; Parameters</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:DropDownList id="ddlCustomer"
Runat="server"
OnSelectedIndexChanged="GridOne" />
<asp:Button id="button1"
Text="Search"
onclick="GetData"
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"
AllowPaging = "True"
PageSize = "5"
PagerStyle-Mode = "NumericPages"
PagerStyle-HorizontalAlign="Center"
PagerStyle-PageButtonCount = "10"
OnPageIndexChanged = "Page_Change">
</asp:DataGrid>
</form>
</body>
</html>

Searching, a DataSet, Paging & Parameters (SQL Server)

Most of the examples on this site use a DataReader when demonstrating parameterized queries (Parameterized Queries Tutorial). However, it’s a little different, using a DataSet with a Select query, using parameterized queries. In this sample, we use the Customers and Orders Table in the Northwind database.

We create both a DataAdapter and a Command object, along with the DataSet, to accomplish this. Naturally, to implement Paging in a DataGrid, we must have a DataSet. First, inside the Page_Load event, and also inside an if/Then/Postback block, we populate a DropDownList with the Items on which we will base the search. Then, in the BindData subroutine, we use the Selected Item from the DropDownList to search and populate the DataSet, which gets bound to the DataGrid and implements Paging.

Also notice, that we have an extra Sub called ‘GridOne’. Here, whenever the DropDownList item is changed, we assume the user is doing a new search. Therefore, we automatically set the CurrentPageIndex of the DataGrid to 0. This way, there aren’t any errors if the current page is higher than the page count in the new search.

Click here for an MS Access version of this code.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<script language="VB" Runat="server">
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 [CustomerID], [CompanyName] from Customers"
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)
ddlCustomer.DataSource = objDR
ddlCustomer.DataValueField="CustomerID"
ddlCustomer.DataTextField="CompanyName"
ddlCustomer.DataBind()
MyConn.Close()
end if
End Sub

Sub Page_Change(sender As Object, e As DataGridPageChangedEventArgs)
MyDataGrid.CurrentPageIndex = e.NewPageIndex
BindData
End Sub
Sub BindData()
Dim strConn as string = "server=YourServer;uid=sa;pwd=YourPWD;database=Northwind"
Dim MySQL as string = "Select * from Orders Where CustomerID = @CustID Order by OrderID "
Dim MyConn as New SQLConnection(strConn)
Dim ds as DataSet=New DataSet()
Dim da as SqlDataAdapter=New SQLDataAdapter
Dim Cmd as New SqlCommand    (MySQL,MyConn)
da.SelectCommand = cmd
cmd.Parameters.Add(New SQLParameter("@CustID", ddlcustomer.SelectedItem.Value))
da.Fill(ds,"Orders")
MyDataGrid.Datasource=ds.Tables("Orders").DefaultView
MyDataGrid.DataBind()
End Sub

Sub GetData(Source as Object, E as EventArgs)
BindData
End Sub

Sub GridOne(Source as Object, E as EventArgs)
MyDataGrid.currentpageindex=0
End Sub

</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 3.2">
<title>Using a DataSet with Parameters</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:DropDownList id="ddlCustomer"
Runat="server"
OnSelectedIndexChanged="GridOne" />
<asp:Button id="button1"
Text="Search"
onclick="GetData"
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"
AllowPaging = "True"
PageSize = "5"
PagerStyle-Mode = "NumericPages"
PagerStyle-HorizontalAlign="Center"
PagerStyle-PageButtonCount = "10"
OnPageIndexChanged = "Page_Change">
</asp:DataGrid>
</form>
</body>
</html>

Retrieving Field Names From a DB Table

Sometimes we need to grab the Field names from an existing table and use them on our ASP.Net pages. For instance, we could add them to a DropDownList, or ListBox, for choices to be made, using that list, by the end user.

This example can be used for any List type ASP.Net control (Listbox, Dropdownlist, etc).

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<script language="VB" Runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
Dim count as Integer
Dim fldName as String
Dim strConn as string = "server=YourServerName;uid=YourUID;pwd=YourPWD;database=NorthWind"
Dim MySQL as string = "Select Top 1 * from Employees"
Dim MyConn as New SQLConnection(strConn)
Dim objDR as SQLDataReader
Dim Cmd as New SQLCommand(MySQL, MyConn)
MyConn.Open()
Try
	objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
	For Count = 0 To objDR.FieldCount-1
		lstFields.Items.Add(objDR.GetName(count))
	Next count
Catch ex as Exception
	response.Write (ex.Message)
Finally
	MyConn.Close()
End Try
End Sub

</script>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.2">
	<title>Retrieving Field Names From a DB Table</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:ListBox id="lstFields" Runat="server" />
</form>
</body>
</html>

DropDownLists with Year, Month and Day

First off, this is an expanded sample from DropDownLists with Current Date and Month

What makes this different, is the addition of the Year DropDownList. Here, when you change the year or month, the number of days changes in the ‘Day’ DropDownList to match the correct number of days, based on not only the month, but the year.

For instance – select Febuary and 2004 or 2008, and you will get 29 days. But, if you choose any years in between those years, you will get 28.

<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.2">
	<title>DropDownLists with Year, Month and Day</title>
<script language="vb" runat="server">
Dim x As Integer
Dim intDay, intMnth as integer
Dim MyDate as DateTime
Dim arr as ArrayList
Dim myYear as Integer
Sub Page_Load(sender As Object, e As EventArgs)

if not Page.IsPostBack then
	intDay=Day(now)
	intMnth = Month(Now)
	Dim MyDate as DateTime
	MyDate=DateTime.Now
	If Not IsPostBack Then
		For x = 1 To 12
			ddMonth.Items.Add(New ListItem(MonthName(x), x))
		Next
		''ddDay.Items.Clear()
		For x = 1 To MyDate.DaysInMonth(MyDate.Year, MyDate.Month)
			ddDay.Items.Add(x)
		Next
		End If
		arr=New Arraylist

		''Next two For/Next Loops add 5 years before and 5 years after current year
		For x = 0 to 5
			arr.add(MyDate.Year-x)
		Next

		For x = 1 to 5
			arr.add(MyDate.Year+x)
		Next
		arr.Sort
		ddYear.DataSource=arr
		ddYear.DataBind

	ddDay.selectedIndex=intDay-1
	ddMonth.selectedIndex=intMnth-1
	ddYear.Items.FindByValue(MyDate.Year).Selected = true
end if
end sub

Sub doDayChange(Source as Object, E as EventArgs)
dayChange
End Sub

Sub dayChange()
if MyYear.ToString.length < 4  then
	MyYear=MyDate.Year
else
	MyYear=ddYear.SelectedItem.Text
End If

MyDate=ddMonth.SelectedItem.Text & "/1/" &  myYear
	ddDay.Items.Clear()
	For x = 1 To MyDate.DaysInMonth(MyDate.Year, MyDate.Month)
		ddDay.Items.Add(x)
	Next
End Sub

Sub doYear(Source as Object, E as EventArgs)
myYear = ddYear.selectedItem.Text
dayChange
End Sub
</script>
</head>
<HTML>
<body>
<form id="Form1" method="post" runat="server">
<table>
	<tr>
		<td align="Left" valign="Top">
			<b>Day:</b></td>
		<td align="Left" valign="Top">
			<b>Month:</b</td>

		<td align="Left" valign="Top">
			<b>Year:</b></td>
	</tr>
	<tr>
		<td align="Left" valign="Top">
			<asp:DropDownList
				ID="ddDay"
				Runat="server">
			</asp:DropDownList></td>
		<td align="Left" valign="Top">
			<asp:DropDownList
				ID="ddMonth"
				OnSelectedIndexChanged="doDayChange"
				Runat="server"
				AutoPostBack="True">
			</asp:DropDownList> </td>

		<td align="Left" valign="Top">
			<asp:DropDownList
				id="ddYear"
				AutoPostBack="True"
				 OnSelectedIndexChanged="doYear"
				Runat="server">
			</asp:DropDownList></td>
	</tr>
</table>
</form>
</body>
</HTML>

Dynamic Editablity With TextBoxes

Sometimes, there comes a need to dynamically make text boxes editable, based on certain criteria. In able to go back and forth between editablity with textboxes, it’s best to cover two areas. The first, naturally, is the ‘ReadOnly’ property of the textbox. You set it to True or False, depending on the criteria. However, it may be confusing to the end-user, if you leave it at that.

To take care of this end, you can add/remove borders with the textboxes, and change the backcolor of the textbox itself, so that the textbox will actually ‘look’ editable (or not). This sample shows one way to accomplish this.

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

Sub MakeReadOnly()
if cbEmailUpdate.Checked="True" then
	txtBusEmail.Backcolor=Color.White
	txtBusEmail.borderwidth=unit.point(1)
	txtBusEmail.BorderColor=Color.Black
	txtHomeEmail.BackColor=Color.White
	txtHomeEmail.borderwidth=unit.point(1)
	txtHomeEmail.BorderColor=Color.Black
	txtBusEmail.BorderStyle=BorderStyle.Solid
	txtHomeEmail.BorderStyle=BorderStyle.Solid
	txtBusEmail.ReadOnly="False"
	txtHomeEmail.ReadOnly="False"
else
	txtBusEmail.borderwidth=unit.point(0)
	txtHomeEmail.borderwidth=unit.point(0)
	txtBusEmail.Backcolor=Color.FromARGB(&H78FFFAF0)
	txtHomeEmail.BackColor=Color.FromARGB(&H78FFFAF0)
	txtBusEmail.BorderStyle=BorderStyle.None
	txtHomeEmail.BorderStyle=BorderStyle.None
	txtBusEmail.ReadOnly="True"
	txtHomeEmail.ReadOnly="True"
End If
End Sub
</script>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.2">
	<title>Dynamic Textbox Editablity</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:panel ID="pnl1"
	 BorderColor="Black"
	 BorderWidth="1"
	 Width="100%"
	 BackColor="#FFFAF0"
	Runat="server">
	<table>
		<tr>
			<td align="Right" valign="Top"><b>Home Email:</b> </td>
			<td align="Left" valign="Top">
				<asp:TextBox
					id="txtHomeEmail"
					Text="john@here.com"
					Runat="server" /></td>
		<tr>
			<td align="Right" valign="Top"><b>Business Email: </b></td>
			<td align="Left" valign="Top">
				<asp:TextBox
				id="txtBusEmail"
				Text="jim@here.com"
				Runat="server" /></td>
		</tr>
	</table>
<asp:Checkbox Text="Update Email Addresses when Saving?"
 	AutoPostBack="True"
	OnCheckedChanged="doBorders"
	TextAlign="right"
	id="cbEmailUpdate"
	Visible="true"
	Runat="server" />
</asp:panel>

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

Selecting the Current Year in a DDL

This sample demonstrates how to use a For/Next Loop to dynamically populate a DropDownlist with a list of years, starting 5 years before the current year, and continuing to 5 years after the current year.

Then, once the DropDownlist is populated, inside an if/then/PostBack block, we select the current year by default.

<script language="VB" Runat="server">
Dim myDate as DateTime
Dim myYear as Integer

Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
	myDate=DateTime.Now()
	Dim x as Integer
	myYear=myDate.Year
	x=myYear-5

	for x=x to (x+10)
		ddlYear.Items.Add(x)
	next x
end if
ddlYear.Items.FindByText(myYear).Selected = true
End Sub
</script>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.2">
	<title>Selecting the Current Year in a DDL</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:DropDownList id="ddlYear" Runat="server"/>
</form>
</body>
</html>

Searching an XML File

If you’ve ever wondered how to search an XML file, like you would a regular database, this sample is for you. We start with an XML file called ‘cars.xml’. The rest, though, is code, not history :)

You can download the xml file here.

<%@ Import Namespace="System.Data" %>

<script language="VB" Runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
	Dim ds as DataSet = new DataSet()
	ds.ReadXml(Server.MapPath("/data/cars.xml"))
	ddlPrice.DataSource=ds
	ddlPrice.DataTextField="Price"
	ddlPrice.DataBind
end if
End Sub

Sub GetCar(Source as Object, E as EventArgs)
	Dim dsProducts as DataSet = new DataSet()
	dsProducts.ReadXml(Server.MapPath("/data/cars.xml"))
	Dim dv as DataView = new DataView(dsProducts.Tables("Products"))
	dv.Sort = "Price"
	Dim rowIndex as integer = dv.Find(ddlPrice.SelectedItem.Text)
	Dim Price, Vehicle as String

if (rowIndex = -1) Then
	Response.Write("Car not found")
else
	ph1.visible="True"
	Price = dv(rowIndex)("Price").ToString()
	lblPrice.text = "Price: " + FormatCurrency(Price) + "<br>"
	Vehicle = dv(rowIndex)("Vehicle").ToString()
	lblCar.text="Vehicle : " + Vehicle
End If
End Sub
</script>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.1">
	<title>Searching an XML File</title>
</head>
<body>
<form id="form1" Runat="server">
<asp:DropDownList id="ddlPrice" Runat="server"/>
<asp:Button id="button1"
	Text="Get Car"
	onclick="GetCar"
	Runat="server" /><br>
<asp:placeholder ID="ph1" Visible="False" Runat="server">
<asp:Label ID="lblCar" Runat="server" /> --
<asp:Label ID="lblPrice" Runat="server" /><br>
</asp:placeholder>
</form>
</body>
</html>

A Simple Image Gallery

One of the great new things about DotNet is its System.Drawing namespace, including the ability to generate thumbnails on the fly, however, when it comes to walking a directory, using that ability isn’t quite as easy as it sounds. <p.
Therefore, this sample is called 'A Simple (or Poor Man's) Image Gallery', to show alternate ways of doing the same thing. We still use the System.Drawing namespace, but for one obsure reason. The HTML image tag doesn't recognize percentages for its height and width attributes. BUT – using the System.Drawing namespace, we can grab the width and height, then perform percentage math on those numbers, and finally place the output into the image tag itself.

<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.IO" %>
<script language="VB" Runat="server">
Dim i As Integer
Dim FileName As String
Dim swidth, sheight As string
Dim path As String
Dim Img as System.Drawing.Image

Sub GetPictures(Source as Object, E as EventArgs)
literal1.text=""

''Here, you define what subdirectory
Dim MainPath as String = "\YourPath\"
path = Server.MapPath(MainPath)
Dim DirInfo As New DirectoryInfo(path)
Dim Files As FileInfo() = DirInfo.GetFiles()
Dim FileWidth as Integer
Dim FileHeight as Integer
Dim count as Integer=0
Dim sNumbers as String
Dim sExt as String
For i = 0 To Files.Length - 1
FileName = path & Files(i).Name
	sExt=FileName.Substring(FileName.Length-3,3)
	if sExt="jpg" or sExt="gif" then
		Img = Img.FromFile(FileName)
		Trace.Warn ("image Height = " & img.Height)
		Trace.Warn ("image Width = " & img.Width)
		if cbHundred.Checked="True" then
			FileHeight=(75)
			FileWidth=(75)
		else
			FileHeight=(.5 * img.Height)
			FileWidth=(.5 * Img.Width)
		End If

		swidth =" width= " & (FileWidth)
		Trace.Write ("width - " & swidth)
		sheight=" height=" & (FileHeight)
		Trace.Write ("height - " & sHeight)

		if count=0 then
			literal1.text+="<tr>"
		End If

		sNumbers = "<br>Orig Width - " & img.Width & "<br>Orig Height - " & _
			img.Height & "<br>Thumb Width - " & FileWidth & "<br>" & _
			"Thumb Height - " & FileHeight

		if cbSizes.Checked="True" then
			literal1.text +="<td valign=''middle'' align=''center''>" & _
			"<a href=" & FileName & " target=""_blank""><img src=" & _
			FileName & swidth & sheight & " border=""0""></a>" & _
			sNumbers & "</td>"
		else
			literal1.text +="<td valign=''middle'' align=''center''>" & _
			"<a href=" & FileName & " target=""_blank""><img src=" & _
			FileName & swidth & sheight & " border=""0""></a></td>"
		End If
		count=count + 1

		''This will control how many images in each row:
		if count=4 then
			literal1.text +="</tr>"
			count=0
		End If
	End If
Next i
End Sub
</script>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.1">
	<title>Simple Image Gallery</title>
</head>
<body>
<form id="form1" Runat="server">
<div align="center">
	<b><font Size="4">All images in Directory</font></b>
		<br>Click on individual image to get full-sized image<hr>
<asp:Checkbox
	Text="Include Sizes"
	id="cbSizes"
	Runat="server" />
<asp:Checkbox
	Text="Ignore Aspect Ratio"
	id="cbHundred"
	Checked="True"
	Runat="server" />
<asp:Button
	id="buttonGetPics"
	Text="Get Pictures"
	onclick="getPictures"
	Runat="server" /><hr>
<table border="1">
<asp:Literal ID="Literal1" Runat="server"/>
</table></div></form>
</body>
</html>

Creating and Writing Text Files

This sample shows how to create a text file from scratch, including writing text in the file. Along with that, we use the ‘if File.Exists(filename) check, before writing the file, in order to make sure we don’t overwrite an existing file with the same name.

Also, we have a look at the Try/Catch error checking method. With this, we are only using the Try and the Catch sections. We could have used a ‘Finally’ section, but there wasn’t a really reason for that, in this case.

<%@ Import Namespace="System.IO" %>
<script language="VB" Runat="server">
Dim sFileName as String
Sub doCreate(Source as Object, E as EventArgs)
sFileName = Server.MapPath("\") & _
	txtName.text & ".txt"
Try
Dim objStreamWriter as StreamWriter
	if file.exists(sFileName) then
		lblResults.text="File already exists"
	else
		objStreamWriter = File.CreateText(sFileName)
		objStreamWriter.Write(txtContents.text)
		objStreamWriter.Close
		lblResults.text="<b>Here is the text of your file:</b><br>"
		ReadFile()
	End If
Catch ex as Exception
	lblResults.text=ex.message
End Try
End Sub

Sub ReadFile()
	Dim objStreamReader As StreamReader
	objStreamReader = File.OpenText(sFileName)
	Dim contents as String = objStreamReader.ReadToEnd()
	lblResults.text += contents
	objStreamReader.Close()
End Sub
</script>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 3.1">
	<title>Creating & Writing a Text File</title>
</head>
<body>
<form id="form1" Runat="server">
Name of File:
<asp:TextBox id="txtName" Runat="server" />
<br>
Enter your text:<br>
<asp:TextBox id="txtContents"
	TextMode="MultiLine"
	Rows="4"
	Width="400"
	Runat="server" />
(<i><font Color=''#FF0000''>do Not enter extension</font></i>)
<p>
<asp:Button id="button"
	Text="Create File"
	onclick="doCreate"
	Runat="server" /><br>
<asp:Label ID="lblResults" Runat="server" />
</form>
</body>
</html>