Change BackGround Color of Page Programmatically

This is mainly an exercise in event driven programming. However, it entails changing the background color of the existing page, which is made possible by adding the runat=server segment to the body tag, along with an id, therefore making it a programmable html control.

Additiionally, this sample uses an ArrayList and binds it to a DropDownList.

<html>
<head>
<meta name=”GENERATOR” Content=”ASP Express 2.0″>
<title>Change BackGround Color of Page</title>
<script language=”VB” runat=”server”>
Sub Page_Load(Source as Object, E as EventArgs)
Dim ColorList as ArrayList= new ArrayList()
if not Page.IsPostBack then
ColorList.Add (“AliceBlue”)
ColorList.Add (“AntiqueWhite”)
ColorList.Add (“Aquamarine”)
ColorList.Add (“BlanchedAlmond”)
ColorList.Add (“CadetBlue”)
ColorList.Add (“Chocolate”)
ColorList.Add (“Crimson”)
ColorList.Add (“SkyBlue”)
dd1.datasource=ColorList
dd1.databind()
end if
End Sub

Sub changecolor(Source as Object, E as EventArgs)
bdy.attributes(“bgcolor”)=dd1.SelectedItem.Text
End Sub
</script>
</head>
<body runat=”server” id=”bdy”>
<div align=”center”><Form id=”form1″ runat=”server”>
<asp:DropDownList id=”dd1″ runat=”server” />
<asp:Button id=”button1″ Text=”Change Background Color” onclick=”changecolor” runat=”server” />
</Form></div>
</body>
</html>

Fill 2nd ListBox based on Selection from First ListBox

Many times we want to choose an item in one listbox, in order to fill another listbox with items that match the criteria selected in the first listbox.

In this example, there are two database tables (Model and BodyStyle) where the actual data is being retrieved. The first listbox is filled on Page_load with the Car Models. Based on the selection from this first listbox, by clicking the button, we retrieve the Body Styles of that particular model.

Just copy this code sample to a new document, import the data (download cardata.zip – includes .sql scripts and data) and change the database/connection information to run it locally on your computer.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 2.0">
<title>Listboxes</title>
<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
Dim strConn as string = "server=(local);uid=sa;pwd=password;database=yourdatabase"
Dim MySQL as string = "Select Model from model"
Dim MyConn as New SQLConnection(strConn)
Dim Cmd as New SQLCommand(MySQL, MyConn)
MyConn.Open()
List1.DataSource = Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
List1.DataBind()
list1.selectedindex=0
end if
End Sub

Sub FillList2(Source as Object, E as EventArgs)
DoFill
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 =’" & list1.selecteditem.text & "’"
Dim MyConn as New SQLConnection(strConn)
Dim Cmd as New SQLCommand(MySQL, MyConn)
MyConn.Open()
List2.DataSource = Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
List2.DataBind()
End Sub
</script>

</head>
<body>
<div align="center"><Form id="form1" runat="server">
<table width="275" border="0">
<tr>
<td align="Left" valign="Top"><b>Choose Model:</b>
<asp:ListBox id="list1" width="125" height="150" datatextfield="Model" runat="server" />
</td>
<td Width="50" align="right" valign="Top"></td>
<td align="Left" valign="Top"><b>Body Styles</b>
<asp:ListBox id="list2" width="125" height="150" Datatextfield="BodyStyle" runat="server" />
</td>
</tr>
<tr>
<td align="center" valign="Top" Colspan="3">
<asp:Button id="button1" Text="Fill Second Listbox" onclick="FillList2" runat="server" />
</td>
</tr>
</table>
</Form>
</div>

</body>
</html>

Changing Page BackGround Color Programmatically

There are several things this sample shows, including creating an arraylist and binding it to a DropDownList, but the main thrust of the sample is to show how to easily change the background color of the existing page programmatically.

<html>
<head>
<meta name=”GENERATOR” Content=”ASP Express 2.0″>
<title>Change Body Color</title>
<script language=”VB” runat=”server”>
Sub Page_Load(Source as Object, E as EventArgs)

if not Page.IsPostBack then
Dim ColorList as ArrayList= new ArrayList()
ColorList.Add (“AliceBlue”)
ColorList.Add (“AntiqueWhite”)
ColorList.Add (“Aquamarine”)
ColorList.Add (“BlanchedAlmond”)
ColorList.Add (“CadetBlue”)
ColorList.Add (“Chocolate”)
dd1.datasource=ColorList
dd1.databind()
end if
End Sub

Sub changecolor(Source as Object, E as EventArgs)
bdy.attributes(“bgcolor”)=dd1.SelectedItem.Text
End Sub
</script>

</head>
<body runat=”server” id=”bdy”>
<Form id=”form1″ runat=”server”>
<asp:DropDownList id=”dd1″ runat=”server” /><asp:Button id=”button1″ Text=”Change Background Color” onclick=”changecolor” runat=”server” />
</Form>
</body>
</html>

Listbox – Selecting Multiple Items

Sometimes, you will come across a need to select multiple items from a ListBox. This code example shows how to create a multi-select Listbox, and also how to iterate through the item collection to retrieve the text values of the selected items.

<html>
<head>
<meta name="GENERATOR" Content="ASP Express 2.0">
<title>Listbox – Selecting Multiple Items</title>
<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
with listbox1.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 ListBox1.Items
If Item.Selected Then
Stuff = Stuff & Item.Text & "<br>"
End If
Next
If Stuff <> "" Then
Label1.Text = "<b>You chose :</b> <br>" & Stuff
Else
Label1.Text = "<b>Hey – Nothing was chosen!</b> "
End If
End Sub

</script>
</head>
<body>
<Form id="form1" runat="server">
<asp:ListBox id="Listbox1"
Height="125px"
width="100px" SelectionMode="Multiple"
runat="server" />
<asp:Button id="button1" Text="Get Items" onclick="doList" runat="server" /><br>
<asp:Label ID="label1" runat="server" />
</Form>
</body>
</html>

Binding String to DropdownList/Using items as Properties

This example shows three things –
1. having a long list of items in a string, and binding them to a DropDownList
2. Using the items as Properties in code
3. Accessing the items in the DropDownlist programmatically

This example uses the long list of colors you can use as properties.
The string is bound to the DropDownList, and then, choosing the color, using the SelectedIndex property from the DropDownList, programmatically, with the Button click events (Next and Previous).
All you need to do is copy the code below into a blank page and run it from your DotNet enabled web server.

<html>
<%@ Import Namespace=”System.Drawing” %>
<head>
<meta name=”GENERATOR” Content=”ASP Express 2.0″>
<title>Binding String to DropdownList/Using items as Properties</title>
<script language=”VB” runat=”server”>
Protected strBColor as string
Sub Page_Load(Source as Object, E as EventArgs)

if not Page.IsPostBack then
Dim LongList() As String ={“AliceBlue”, “AntiqueWhite”, “Aqua”, “Aquamarine”, “Azure”, “Beige”, “Bisque”, “Black”,”BlanchedAlmond”,”Blue”,”BlueViolet”,”Brown”,”BurlyWood”,”CadetBlue”,”Chartreuse”,”Chocolate”,”Coral”,”CornflowerBlue”,”Cornsilk”,”Crimson”,”Cyan”,”DarkBlue”,”DarkCyan”,”DarkGoldenrod”,”DarkGray”,”DarkGreen”,”DarkKhaki”,”DarkMagenta”,”DarkOliveGreen”,”DarkOrange”,”DarkRed”,”DarkSalmon”,”DarkSeaGreen”,”DarkSlateBlue”,”DarkSlateGray”,”DarkTurquoise”,”DarkViolet”,”DeepPink”,”DeepSkyBlue”,”DimGray”,”DodgerBlue”,”FireBrick”,”FloralWhite”,”ForestGreen”,”Fuchsia”,”Gainsboro”,”GhostWhite”,”Gold”,”Goldenrod”,”Gray”,”Green”,”GreenYellow”,”HoneyDew”,”HotPink”,”IndianRed”,”Indigo”,”Ivory”,”Khaki”,”Lavender”,”LavenderBlush”,”LawnGreen”,”LemonChiffon”,”LightBlue”,”LightCoral”,”LightCyan”,”LightGoldenrodYellow”,”LightGray”,”LightGreen”,”LightPink”,”LightSalmon”,”LightSkyBlue”,”LightSteelBlue”,”LightYellow”,”Lime”,”LimeGreen”,”Linen”,”Magenta”,”Maroon”,”MediumAquamarine”,”MediumBlue”,”MediumOrchid”,”MediumPurple”,”MediumSeaGreen”,”MediumSlateBlue”,”MediumSpringGreen”,”MediumTurquoise”,”MediumVioletRed”,”MidnightBlue”,”MintCream”,”MistyRose”,”Moccasin”,”NavajoWhite”,”Navy”,”OldLace”,”Olive”,”OliveDrab”,”Orange”,”OrangeRed”,”Orchid”,”PaleGoldenrod”,”PaleGreen”,”PaleTurquoise”,”PaleVioletRed”,”PapayaWhip”,”PeachPuff”,”Peru”,”Pink”,”Plum”,”PowderBlue”,”Purple”,”Red”,”RosyBrown”,”RoyalBlue”,”SaddleBrown”,”Salmon”,”SandyBrown”,”SeaGreen”,”SeaShell”,”Sienna”,”Silver”,”SkyBlue”,”SlateGray”,”Snow”,”SpringGreen”,”SteelBlue”,”Tan”,”Teal”,”Thistle”,”Tomato”,”Turquoise”,”Violet”,”Wheat”,”White”,”WhiteSmoke”,”Yellow”,”YellowGreen”}
dd1.datasource=LongList
dd1.databind()
doLabels
end if
End Sub

Sub doLabels()
Label1.Text = “You selected ” & dd1.SelectedItem.Text
Label1.BackColor = Color.FromName(dd1.SelectedItem.Text)
dd1.BackColor = Color.FromName(dd1.SelectedItem.Text)
Label2.Text = “Selected Index = ” & dd1.SelectedIndex & _
” of (Item Count) ” & dd1.Items.Count – 1
End Sub

Sub dd1_SelectedIndexChanged(Source as Object, E as EventArgs)
doLabels
End Sub

Sub Button1_Click(Source as Object, E as EventArgs)
strBColor = dd1.SelectedItem.Text
If dd1.SelectedIndex <> dd1.Items.Count – 1 Then
dd1.SelectedIndex = dd1.SelectedIndex + 1
Else
dd1.SelectedIndex = dd1.SelectedIndex
End If
doLabels
End Sub

Sub Button2_Click(Source as Object, E as EventArgs)
If dd1.SelectedIndex <> 0 Then
dd1.SelectedIndex = dd1.SelectedIndex – 1
dolabels
End If
End Sub
</script>
</head>
<body>

<Form id=”form1″ runat=”server”>
<asp:DropDownList id=”dd1″ autopostback=”true” OnSelectedIndexChanged=”dd1_SelectedIndexChanged” runat=”server” />
<asp:Button id=”button1″ Text=”Next Color” onclick=”button1_click” tabindex=”0″ runat=”server” />
<asp:Button onclick=”button2_click” id=Button2 runat=”server” Width=”92″ Height=”25px” Text=”Previous Color”></asp:Button><p>
<asp:Label id=Label1 runat=”server” Width=”449px” Height=”75px” BorderStyle=”Groove” Font-Size=”Large” Font-Names=”Verdana” Font-Italic=”True” Font-Bold=”True”></asp:Label><br>
<asp:Label ID=”label2″ runat=”server” />
</Form>

</body>
</html>

2 Listboxes – Moving Items From One to Another

Many times we need to create a page and choose items from a listbox, moving them to the other one. This code sample shows how to not only copy the items over to the other one, but remove them from listbox1 also. For simplicity’s sake, the items shown here, are manually added in the Page_Load event.

Just copy this code straight from the page into a new file, save it with the ASPX extension and try it out!

<html>
<head>
<meta name="GENERATOR" Content="ASP Express 2.0">
<title>Untitled</title>
<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
If Not Page.IsPostBack Then
Dim intFirst As Integer
For intFirst = 1 To 10
ListBox1.Items.Add("Item " & intFirst)
Next
End If
End Sub

Sub button1_click(Source as Object, E as EventArgs)
Dim li As ListItem
For Each li In ListBox1.Items
If li.Selected = True Then
ListBox2.Items.Add(li.Text)
End If
Next

Dim counter As Integer
For counter = (ListBox1.Items.Count – 1) To 0 Step -1
If ListBox1.Items(counter).Selected = True Then
ListBox1.Items.RemoveAt(counter)
End If
Next
End Sub

Sub button2_click(Source as Object, E as EventArgs)
Dim counter As Integer
Dim li As ListItem

For Each li In ListBox2.Items
If li.Selected = True Then
ListBox1.Items.Add(li.Text)
End If
Next

For counter = (ListBox2.Items.Count – 1) To 0 Step -1
If ListBox2.Items(counter).Selected = True Then
ListBox2.Items.RemoveAt(counter)
End If
Next
End Sub
</script>
</head>
<body>
<div align="center"><Form id="form1" runat="server">
<table cellpadding="2" cellspacing="2" border=0>
<tr>
<td align="center" valign="top"><asp:ListBox id="ListBox1" width="125px" height="175" SelectionMode="Multiple" runat="server" /></td>
<td align="center" valign="center"><asp:Button id="button1" width="88px" height="26" Text="Add >>" onclick="button1_click" runat="server" /><br>
<asp:Button id="button2" Text="<< Remove" onclick="button2_click" width="88px" height="26" runat="server" />
</td>
<td align="center" valign="top"><asp:ListBox id="Listbox2" width="125px" height="175" SelectionMode="Multiple" runat="server" /></td>
</tr>
</table>
</Form></div>
</body>
</html>

DataGrid – Programmatic Property Changes

There are many times which you might need to change the properties of an ASP.Net WebControl. There are many more properties available in ASP.Net than there are in pure HTML. Also, if you’ve ever programmed in VB (before DotNet), Though the concept is pretty much the same, The path to get to where you are going is quite different in some cases.

Remember, if you want to do any programmatic color changes, you must do a System.Drawing Import (<%@ Import Namespace=”System.Drawing” %>). In all cases, checking out the Class Browser in the Quickstart Tutorials will help you get a feel of the syntax needed for each control. Check out the syntax used in the example below, then, go over to the Class Browser for Web Controls – choose TextBox and you’ll see what I mean by drilling down through the properties.

As always, in order to try it out, merely copy the following code directly into a blank page, change the data connection code for your ownsituation, save it as an aspx file and run it from your web server. Naturally, we recommend using ASP Express for this.

<%@ Import Namespace=”System.Data” %>
<%@ Import Namespace=”System.Data.SQLClient” %>
<%@ Import namespace=”System.Drawing” %>

<!– Created: 06/18/2002 11:15:26 PM –>
<html>
<head>
<meta name=”GENERATOR” Content=”ASP Express 2.0″>
<title>TEST Page</TITLE>
<script language=”VB” runat=”server”>
Public strAltClr as string
Sub Page_Change(sender As Object, e As DataGridPageChangedEventArgs)
MyDataGrid.CurrentPageIndex = e.NewPageIndex
BindData
End Sub

Sub Page_Load(Source As Object, E As EventArgs)
If Not Page.IsPostBack Then
BindData()
End If
End Sub

Sub BindData()
Dim strConn as string = “server=(local);uid=sa;pwd=;database=pubs”
Dim MySQL as string = “Select au_fname, au_lname, phone, state from authors”
Dim MyConn as New SQLConnection(strConn)
Dim ds as DataSet=New DataSet()
Dim Cmd as New SQLDataAdapter(MySQL,MyConn)
Cmd.Fill(ds,”authors”)
MyDataGrid.Datasource=ds.Tables(“authors”).DefaultView
MyDataGrid.DataBind()
End Sub

Sub Button1_Click(sender As Object, e As System.EventArgs)
Dim intHeaderSize As Integer
Dim intNewSize As Integer
Dim intAltSize As Integer
Dim strGridLines As String

strAltClr=GClr.SelectedItem.Text

With MyDataGrid
intHeaderSize = HeaderSize.SelectedItem.Text
strGridLines = GLines.SelectedItem.Text
intAltSize = AltSize.SelectedItem.Text
intNewSize = GridSize.SelectedItem.Text
MyDataGrid.Font.Size = FontUnit.Point (intNewSize)

MyDataGrid.HeaderStyle.Font.Size = FontUnit.Point (intHeaderSize)
MyDataGrid.AlternatingItemStyle.Font.Size = FontUnit.Point (intAltSize)

if strAltClr=”Reset” then strAltClr=”LightGray”
.AlternatingItemStyle.BackColor = Color.FromName(strAltClr)

Select Case GLines.SelectedItem.Text
Case “None”
.GridLines = GridLines.None
Case “Both”
.GridLines = GridLines.Both
Case “Horizontal”
.GridLines = GridLines.Horizontal
Case “Vertical”
.GridLines = GridLines.Vertical
End Select

End With
End Sub

</script>
</head>
<body>
<div align=”center”><form runat=”server” method=”post”>
<asp:Datagrid runat=”server”
Width=”75%”
Id=”MyDataGrid”
cellpadding=”2″
cellspacing=”0″
Headerstyle-BackColor=”#8080C0″
Headerstyle-Font-Name=”Arial”
Headerstyle-Font-Bold=”True”
BackColor=”#8080FF”
Font-Name=”Arial”
Font-Bold=”True”
AlternatingItemStyle-BackColor=”LightGray”
AlternatingItemStyle-Font-Name=”Arial”
AlternatingItemStyle-Font-Bold=”True”
BorderColor=”Black”
AllowPaging = “True”
PageSize = “10″
PagerStyle-Mode = “NumericPages”
PagerStyle-PageButtonCount = “10″
PagerStyle-Font-Size=”12″
PagerStyle-HorizontalAlign=”Center”
PagerStyle-BackColor=”LightGoldenrodYellow”
OnPageIndexChanged = “Page_Change”>
</asp:DataGrid>

<table cellpadding=”2″ cellspacing=”2″ border=”0″ width=”75%”>
<tr>

<td valign=”top” Align=”Center”><b>Alternating BackColor:</b><br>
<asp:dropdownlist id=”Gclr” 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>Reset</asp:listitem>
</asp:dropdownlist></td>

<td valign=”top” Align=”Center”><b>Header FontSize:</b><br>
<asp:dropdownlist id=”HeaderSize” 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>20</asp:listitem>
<asp:listitem>24</asp:listitem>
</asp:dropdownlist></td>
<td valign=”top” Align=”Center”><b>Grid FontSize:</b><br>
<asp:dropdownlist id=”GridSize” 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>20</asp:listitem>
<asp:listitem>24</asp:listitem>
</asp:dropdownlist></td>
<td valign=”top” Align=”Center”><b>Alternating Item Font Size:</b><br>
<asp:dropdownlist id=”AltSize” 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>20</asp:listitem>
<asp:listitem>24</asp:listitem>
</asp:dropdownlist><p>
</td>
<td valign=”top” Align=”Center”><b>Grid Lines:</b><br>
<asp:dropdownlist id=”GLines” runat=”server”>
<asp:listitem>None</asp:listitem>
<asp:listitem>Horizontal</asp:listitem>
<asp:listitem>Vertical</asp:listitem>
<asp:listitem>Both</asp:listitem>
</asp:dropdownlist></td>
</tr>
</table><br>
<br>
<asp:Button id=”button1″ Text=”Submit” onclick=”Button1_Click” runat=”server” />
</form>

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

TextBox – Programmatic Property Changes

There are many times which you might need to change the properties of an ASP.Net WebControl. There are many more properties available in ASP.Net than there are in pure HTML. Also, if you’ve ever programmed in VB (before DotNet), Though the concept is pretty much the same, The path to get to where you are going is quite different in some cases.

Remember, if you want to do any programmatic color changes, you must do a System.Drawing Import (<%@ Import Namespace=”System.Drawing” %>). In all cases, checking out the Class Browser in the Quickstart Tutorials will help you get a feel of the syntax needed for each control. Check out the syntax used in the example below, then, go over to the Class Browser for Web Controls – choose TextBox and you’ll see what I mean by drilling down through the properties.

As always, in order to try it out, merely copy the following code directly into a blank page, save it as an aspx file and run it from your web server. Naturally, we recommend using ASP Express for this.

<%@ Import Namespace=”System.Drawing” %>
<html>
<head>
<meta name=”GENERATOR” Content=”ASP Express 2.0″>
<title>Text Box Programmatic Changes</title>
<script language=”VB” runat=”server”>
Sub Button1_click(Source as Object, E as EventArgs)
text1.BackColor=Color.FromName(BC.SelectedItem.text)
text1.forecolor=color.white
text1.bordercolor=color.blue
text1.borderwidth=unit.point(bW.selecteditem.text)
text1.height=unit.point(100)
text1.width=unit.point(500)
text1.Font.Size = FontUnit.Point (FS.SelectedItem.text)
End Sub
</script>
</head>
<body>
<Form id=”Form1″ runat=”server”>
<table with=”75%” border=”1″> <tr>
<td align=”Center” valign=”Top”><b>Border Width:</b><br>
<asp:dropdownlist id=”bW” runat=”server”>
<asp:listitem selected=”true”>2</asp:listitem>
<asp:listitem>3</asp:listitem>
<asp:listitem>5</asp:listitem>
<asp:listitem>7</asp:listitem>
<asp:listitem>10</asp:listitem>
</asp:dropdownlist></td>
<td align=”Center” valign=”Top”><b>Font Size:</b><br>
<asp:dropdownlist id=”FS” runat=”server”>
<asp:listitem selected=”true”>24</asp:listitem>
<asp:listitem>48</asp:listitem>
<asp:listitem>56</asp:listitem>
<asp:listitem>72</asp:listitem>
</asp:dropdownlist></td>

<td align=”Center” valign=”Top”><b>BackColor:</b> <br>
<asp:dropdownlist id=”BC” runat=”server”>
<asp:listitem selected=”true”>Gray</asp:listitem>
<asp:listitem>Khaki</asp:listitem>
<asp:listitem>Blue</asp:listitem>
<asp:listitem>Black</asp:listitem>
<asp:listitem>Green</asp:listitem>
<asp:listitem>AntiqueWhite</asp:listitem>
<asp:listitem>LightGray</asp:listitem>
</asp:dropdownlist>
</td>
</tr>
</table>

<asp:TextBox id=”text1″ style=”text-align:center” text=”This is the text” runat=”server” /><br>
<asp:Button id=”Button1″ Text=”Submit” onclick=”button1_click” runat=”server” />
</Form>
</body>
</html>

Search from TextBox – Display with Datagrid

Just copy and paste this code into a new blank page. Change the Database name, UID and password. It uses the pubs database with SQL Server and save it as a ‘.aspx’ page.

This code will, upon loading the page, present you with a Text Box, where you will enter a last name. In this particular search, the lastname field in the database is what is searched. Then, based on the search criteria, will search for all authors with the last name chosen, displaying all items in a Datagrid.

As you will also see, if you type in a name that is not actually listed in the table, you will see how to handle this problem with an if/then statement.

SQL Server

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<head>
<script language="VB" runat="server">
Sub doQuery(Source as Object, E as EventArgs)
Dim DS As DataSet
Dim MyConnection As SqlConnection
Dim MyCommand As SqlDataAdapter
Dim strName as string
strName=Name.Text
Label1.Text="You searched for : " + strName
Dim MySQL as string
MySQL="select * from Authors where au_lname =’" & strName & "’"
panel1.visible="true"
label2.text=MySQL
MyConnection = New SqlConnection("server=localhost;uid=sa;pwd=pwd;database=pubs;")
MyCommand = New SqlDataAdapter(MySQL, MyConnection)
DS = new DataSet()
MyCommand.Fill(ds, "Authors")
if ds.tables(0).rows.count>0 then
MyDataGrid.DataSource=ds.Tables("Authors").DefaultView
MyDataGrid.DataBind()
else
lblResults.text="Sorry – no Data Found!"
End if
End Sub

</script>
<title>ASP Express.com – Search a Database – Display Results in a DataGrid Control</title>
</head>

<body>

<h3><font face="Verdana">Search a Database – Display Results in a DataGrid Control</font></h3>
<Form id="form" runat="server">
<asp:textbox id="Name" runat="server" />
<asp:Button id="button" Text="Search" onclick="doQuery" runat="server" />
</Form>
<b>Hint:</b> :<br>
<i>Type in White, Greene, Hunter, Stringer, Smith or Carson</i>
<asp:Panel ID="Panel1" runat="server" visible="False">
<hr>

<div align="center"><b><i>Search Results</i></b>
<asp:Label ID="label1" runat="server" /><br>
<asp:Label ID="label2" runat="server" /><p>

<ASP:DataGrid id="MyDataGrid" runat="server"
Width="700"
BackColor="#ccccff"
BorderColor="black"
ShowFooter="false"
CellPadding=3
CellSpacing="0"
Font-Name="Verdana"
Font-Size="8pt"
HeaderStyle-BackColor="#aaaadd"
EnableViewState="false"
/>
</div>
<b><i><asp:Label ID="lblResults" runat="server" /></i></b>
</asp:Panel>

</body>
</html>

With MS Access, replace the code at the top with:

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<html>
<head>
<script language="VB" runat="server">
Sub doQuery(Source as Object, E as EventArgs)
Dim DS As DataSet
Dim MyConnection As OleDbConnection
Dim MyCommand As OleDbDataAdapter
Dim strName as string
strName=Name.Text
Label1.Text="You searched for : " + strName
Dim MySQL as string
MySQL="select * from Authors where au_lname =’" & strName & "’"
panel1.visible="true"
label2.text=MySQL
MyConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & server.mappath("\biblio.mdb") & ";")
MyCommand = New OleDbDataAdapter(MySQL, MyConnection)
DS = new DataSet()
MyCommand.Fill(ds, "Authors")
if ds.tables(0).rows.count>0 then
MyDataGrid.DataSource=ds.Tables("Authors").DefaultView
MyDataGrid.DataBind()
else
lblResults.text="Sorry – no Data Found!"
End if
End Sub
</script>

Search from DropDown List – Display with Datagrid

Just copy and paste this code into a new blank page. Change the Database name, UID and password. It uses the pubs database with SQL Server and save it as a ‘.aspx’ page.

This code will, upon loading the page, fill a DropDown List with the States from the authors table. Then, based on the search criteria, will search for all authors from the state chosen, displaying all items in a Datagrid.

<%@ Page Debug=”False” Trace=”False” %>

<%@ Import Namespace=”System.Data” %>
<%@ Import Namespace=”System.Data.SqlClient” %>
<html>
<script language=”VB” runat=”server”>

Sub Page_Load(Sender As Object, E As EventArgs)
if not Page.IsPostBack then
doData()
end if
End Sub

Sub doQuery(Source as Object, E as EventArgs)
Dim DS As DataSet
Dim MyConnection As SqlConnection
Dim MyCommand As SqlDataAdapter
Dim strState as string
strState=state.SelectedItem.Text
‘label1.text=”State queried is : ” & strState
Label1.Text=”You chose: ” + strState

Dim MySQL as string
MySQL=”select * from Authors where state=’” & strState & “‘”
panel1.visible=”true”
label2.text=MySQL
MyConnection = New SqlConnection(“server=localhost;uid=userid;pwd=pwd;database=pubs;”)
MyCommand = New SqlDataAdapter(MySQL, MyConnection)
DS = new DataSet()
MyCommand.Fill(ds, “Authors”)

MyDataGrid.DataSource=ds.Tables(“Authors”).DefaultView
MyDataGrid.DataBind()

End Sub

Sub doData()
Dim strConn as string =”server=localhost;database=pubs;uid=sa;pwd=password”
Dim Conn as new SQLconnection(strConn)

Dim strSQL as string =”select distinct state from authors”
Dim Cmd as New SQLCommand(strSQL,Conn)
Conn.Open()
state.DataSource = Cmd.ExecuteReader()
state.DataBind()
End Sub
</script>

<body>

<h3><font face=”Verdana”>Search & Database – Display Results in a DataGrid Control</font></h3>
<Form id=”form” runat=”server”>
<asp:DropDownList id=”state” datatextfield=”state” runat=”server” />
<asp:Button id=”button” Text=”Select State” onclick=”doQuery” runat=”server” />
</Form>
<asp:Panel ID=”Panel1″ runat=”server” visible=”False”>
<hr>

<div align=”center”><b><i>Search Results</i></b>
<asp:Label ID=”label1″ runat=”server” /><br>
<asp:Label ID=”label2″ runat=”server” /><p>

<ASP:DataGrid id=”MyDataGrid” runat=”server”
Width=”700″
BackColor=”#ccccff”
BorderColor=”black”
ShowFooter=”false”
CellPadding=3
CellSpacing=”0″
Font-Name=”Verdana”
Font-Size=”8pt”
HeaderStyle-BackColor=”#aaaadd”
EnableViewState=”false”
/>
</div>
</asp:Panel>

</body>
</html>