DataSet/DataGrid Row Count Check

When binding a DataSet to a DataGrid, if there are no records in the DataSet, it would be nice to present a message telling the end user that, indeed, there were no records that matched his/her query. This code sample uses the Northwind.mdb database (OleDb) to show just that.

This sample also shows how to use a For/Next loop to fill a DropDownList with numbers from 1 to 12.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDB" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.1">
	<title>DataSet/DataGrid Row Count Check</title>
<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
Dim x as integer
if not Page.IsPostBack then
	for x=1 to 12
		ddl1.items.add(x)
	next x
end if
End Sub

Sub BindData(Source as Object, E as EventArgs)
Dim strConn as string = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
server.mappath("/data/northwind.mdb") & ";"
Dim sql as string = "Select * from Categories where categoryID=" & ddl1.selecteditem.text
Dim conn as New OleDBConnection(strConn)
Dim ds as DataSet=New DataSet()
Dim Cmd as New OleDBDataAdapter(sql,conn)
Cmd.Fill(ds,"Categories")
MyDataGrid.Datasource=ds.Tables("Categories").DefaultView
if ds.tables("Categories").rows.count >0 then
	MyDataGrid.DataBind()
	MyDataGrid.visible="true"
	Label1.text=sql
else
	Label1.text=sql & "<br><i><font Color=""#FF0000"">Sorry - no items exist with that Category Number.</font></i>"
	MyDataGrid.visible="false"
End If
End Sub
</script>
</head>
<body>
<form runat="server" method="post">
<b>Choose Category ID: </b><asp:DropDownList id="ddl1" runat="server" />
<asp:Button id="button1" Text="Choose" onclick="BindData" runat="server" />
<asp:Datagrid runat="server"
	Id="MyDataGrid"
	GridLines="Both"
	cellpadding="0"
	cellspacing="0"
	Headerstyle-BackColor="#8080C0"
	Headerstyle-Font-Name="Arial"
	Headerstyle-Font-Size="12"
	BackColor="#8080FF"
	Font-Name="Arial"
	Font-Size="10"
	BorderColor="Black">
</asp:DataGrid>
</form>
<asp:Label ID="label1"  runat="server" />
</body>
</html>

Login Form (SQL Server and OleDb)

This code sample covers many areas of programming in ASP.Net along the way of showing how to create a login page/signup page for your web site.

There are multiple placeholders in the code sample. Each one is visible or invisible, depending on which function is desired at the time. The Sign up section is in one placeholder, where the actual login section is in another. Linkbuttons are used to hide or show each one as needed and if the login is successful – a session is started. On each subsequent page, the code is then shown on how to use the session to make sure the person has logged in successfully.

There are two pages you’ll need to create on your system. It doesn’t really matter what you name the first one, but if you copy the code as is, you’ll need to name the second page ‘logintutorial2.aspx’. The table that was created to hold the data is called ‘logintutorial’ and has the following fields:
id (identity), fname, lname, email, uid, pwd

Changes for using this with MS Access (OleDb Managed Provider) are as follows:
Change the Namespace Imports to:<br?

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

Then, the two Subs (doSignup and doLogin) would have these changes:

Sub doSignup(Source as Object, E as EventArgs)
	Dim strFname as string=frmfname.text
	Dim strLname as string =frmlname.text
	Dim strEmail as string =frmemail.text
	Dim struid as string =frmuid.text
	Dim strpwd as string =frmpwd.text

	Dim MySQL as string = "Insert into logintutorial (fname, lname, email, uid, pwd) values ('" & _
strfname & "', '" & strlname & "', '" & strEmail & "', '" & struid & "', '" & strpwd & "')"
	Dim myConn As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & server.mappath("\loginTutorial.mdb") & ";")
	Dim Cmd as New OleDbCommand(MySQL, MyConn)
	MyConn.Open()
	cmd.ExecuteNonQuery
	label1.text = "

It's Done!"
End Sub
Sub dologin(Source as Object, E as EventArgs)
Dim strConn as string = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & server.mappath("\loginTutorial.mdb") & ";"
Dim MySQL as string = "Select uid, pwd, fname from loginTutorial " & _
"Where uid = '"  & lguid.text & "' and pwd = '" & lgPWD.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)

if Not objDR.Read() then
	 label1.text = "Sorry - your user ID & password were not found"
	objDR.Close
	Myconn.Close
else
	objDR.close
	Myconn.Open
	objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
	While objDR.Read()
		strFname=objDR("fname")
	End While
	Session("ok") ="yes"
	session("Fname")=strFname
	ph3.visible="true"
	ph2.visible="false"
End If
End Sub

Download the MS Access Database to test with:
Logintutorial.zip

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 2.1">
<title>Login Tutorial</title>
<script language="VB" runat="server">
Dim strFname as string
Sub doSignup(Source as Object, E as EventArgs)
Dim strFname as string=frmfname.text
Dim strLname as string =frmlname.text
Dim strEmail as string =frmemail.text
Dim struid as string =frmuid.text
Dim strpwd as string =frmpwd.text

Dim MySQL as string = "Insert into logintutorial (fname, lname, email, uid, pwd) values (‘" & _
strfname & "’, ‘" & strlname & "’, ‘" & strEmail & "’, ‘" & struid & "’, ‘" & strpwd & "’)"
Dim myConn As SqlConnection = New SqlConnection(YourConnectionString)
Dim Cmd as New SQLCommand(MySQL, MyConn)
MyConn.Open()
cmd.ExecuteNonQuery
label1.text = "<p>It’s Done!"
End Sub

Sub newsignup(Source as Object, E as EventArgs)
ph1.visible="true"
ph2.visible="false"
ph3.visible="false"
label1.text=""
End Sub

Sub showlogin(Source as Object, E as EventArgs)
ph2.visible="true"
ph1.visible="false"
label1.text=""
End Sub

Sub dologin(Source as Object, E as EventArgs)
Dim strConn as string = "server=YourServer;uid=uid;pwd=yourpwd;database=yourdb"
Dim MySQL as string = "Select uid, pwd, fname from loginTutorial " & _
"Where uid = ‘" & lguid.text & "’ and pwd = ‘" & lgPWD.text & "’"
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)

if Not objDR.Read() then
label1.text = "<i>Sorry – your user ID & password were not found</i>"
objDR.Close
Myconn.Close
else
objDR.close
Myconn.Open
objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
While objDR.Read()
strFname=objDR("fname")
End While
Session("ok") ="yes"
session("Fname")=strFname
ph3.visible="true"
ph2.visible="false"
End If
End Sub

</script>

</head>
<body>
<form Name="frmSignup" runat="server">
<asp:LinkButton id="login" Text="Login Here" onclick="showlogin"
causesvalidation="false" runat="server" /><br>
<asp:LinkButton id="signup" Text="If you don’t have an account – sign up here"
causesvalidation="false" onclick="newsignup" runat="server" />
<p>
<asp:placeholder ID="ph1" visible="false" runat="server">
<table>
<tr>
<td align="right"><b>First Name:</b> </td>
<td> <asp:textbox id="frmfname" runat="server" />
<asp:RequiredFieldValidator runat="server" id="vldfname"
ControlToValidate="frmfname" ErrorMessage="fname is required" display="Dynamic">
The fname field is Required!
</asp:RequiredFieldValidator></td>
</tr>
<tr>
<td align="right"><b>Last Name: </b></td>
<td> <asp:textbox id="frmlname" runat="server" />
<asp:RequiredFieldValidator runat="server" id="vldlname"
ControlToValidate="frmlname" ErrorMessage="lname is required" display="Dynamic">
The lname field is Required!
</asp:RequiredFieldValidator></td>
</tr>
<tr>
<td align="right"><b>Email</b></td>
<td> <asp:textbox id="frmemail" runat="server" />
<asp:RequiredFieldValidator runat="server" id="vldemail"
ControlToValidate="frmemail" ErrorMessage="email is required" display="Dynamic">
The email field is Required!
</asp:RequiredFieldValidator></td>
</tr>
<tr>
<td align="right"><b>UserID</b> (10 char max):</td>
<td> <asp:textbox id="frmuid" runat="server" />
<asp:RequiredFieldValidator runat="server" id="vlduid"
ControlToValidate="frmuid" ErrorMessage="uid is required" display="Dynamic">
The uid field is Required!
</asp:RequiredFieldValidator></td>
</tr>
<tr>
<td align="right"><b>Password </b>(10 char max):</td>
<td> <asp:textbox id="frmpwd" runat="server" />
<asp:RequiredFieldValidator runat="server" id="vldpwd"
ControlToValidate="frmpwd"
ErrorMessage="pwd is required" display="Dynamic">
The pwd field is Required!
</asp:RequiredFieldValidator></td>
</tr>
<tr>
<td align="right">
<asp:button id="button1"
Text="Submit" onclick="doSignup" runat="server" /></td>
<td></td>
</tr>
</table>
</asp:placeholder>

<asp:placeholder ID="ph2" visible="false" runat="server">
<b>Login:</b><br>

<table border="0"> <tr>
<td align="right" valign="Top"><b>User ID: </b></td>
<td align="Left" valign="Top"><asp:TextBox id="lguid" runat="server" /></td>
</tr>
<tr>
<td align="Right" valign="Top"><b>Password: </b></td>
<td align="Left" valign="Top"><asp:TextBox id="lgpwd" runat="server" /></td>
</tr>
<tr>
<td align="Right" valign="Top" Colspan="2">
<asp:Button id="buttonlg" Text="Login" onclick="dologin" runat="server" /></td>
</tr>

</table>
</asp:placeholder>

<asp:placeholder ID="ph3" visible="false" runat="server">
<A HREF="logintutorial2.aspx">Go to Next Page</A>
</asp:placeholder>
</form><asp:Label ID="label1" runat="server" />
</body>
</html>

Second Page:

<html>
<head>
<meta name="GENERATOR" Content="ASP Express 2.1">
<title>Second page – Login Tutorial</title>
<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
if session("ok") <> "yes" then
label1.text="Sorry – you’re not authorized to be here<br><a href=""logintutorial.aspx"">Go to the login page</a>"
else
label1.text="Welcome to our site, " & session ("fname") & "<p>"
label1.text+="<b><i>You’re authorized to be here</i></b>"

End If
End Sub
</script>
</head>
<body>
<asp:Label ID="label1" runat="server" />
</body>
</html>

Updating/Editing From a DataGrid

Updated Code Sample – using a Parameterized Query!
This code sample uses the Northwind Database Employee table and SQL Server (surprise!).

Several things are necessary for creating these features in the DataGrid. First, you just add an ‘Edit/Update/Cancel’ button column to the grid. Second, for each of those options (Edit/Update/Cancel), you need to create a subroutine that takes care of that particular task. In this case, they are MyDataGrid_EditCommand, MyDataGrid_Cancel, and MyDataGrid_UpdateCommand. The first two are fairly self-explanatory, but the last one, the UpdateCommand, has the real ‘meat’ of this code sample. It provides the actual code for updating the database.

Also, another neat thing that you will probably notice, is it shows how to put an image into the EditText area of the EditColumn. To use this image, just right click on the Pencil and save the image to your computer.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.1">
	<title>Untitled</title>

<script language="VB" runat="server">
Sub MyDataGrid_EditCommand(s As Object, e As DataGridCommandEventArgs )
	MyDataGrid.EditItemIndex = e.Item.ItemIndex
	BindData
End Sub
Sub MyDataGrid_Cancel(Source As Object,   E As DataGridCommandEventArgs)
	MyDataGrid.EditItemIndex = -1
	BindData()
End Sub

Sub MyDataGrid_UpdateCommand(s As Object, e As DataGridCommandEventArgs )
	Dim conn As SqlConnection
	Dim MyCommand As SqlCommand
	Dim strConn as string = "server=YourServer;uid=UID;pwd=PWD;database=Northwind"
	Dim txtFirstName As textbox = E.Item.cells(2).Controls(0)
	Dim txtLastName As textbox = E.Item.cells(3).Controls(0)
	Dim txtTitle As textbox = E.Item.cells(4).Controls(0)
	Dim strUpdateStmt As String
        strUpdateStmt =" UPDATE Employees SET" & _
        " FirstName =@Fname, LastName =@Lname, Title = @Title " & _
        " WHERE EmployeeID = @EmpID"
	conn = New SqlConnection(strConn)
	MyCommand = New SqlCommand(strUpdateStmt, conn)
	MyCommand.Parameters.Add(New SQLParameter("@Fname", txtFirstName.text))
	MyCommand.Parameters.Add(New SQLParameter("@Lname", txtLastName.text))
	MyCommand.Parameters.Add(New SQLParameter("@Title", txtTitle.text))
	MyCommand.Parameters.Add(New SQLParameter("@EmpID", e.Item.Cells(1).Text ))
	conn.Open()
	MyCommand.ExecuteNonQuery()
	MyDataGrid.EditItemIndex = -1
        conn.close
	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=YourServer;uid=UID;pwd=PWD;database=Northwind"
Dim sql as string = "Select EmployeeID, FirstName, LastName, Title from Employees"
  Dim conn as New SQLConnection(strConn)
  Dim objDR as SQLDataReader
  Dim Cmd as New SQLCommand(sql, conn)
  conn.Open()
  objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
  MyDataGrid.DataSource = objDR
  MyDataGrid.DataBind()
  conn.close
End Sub
</script>
</head>
<body><div align="center">
<form runat="server" method="post">
<asp:Datagrid runat="server"
	Id="MyDataGrid"
	GridLines="Both"
	cellpadding="0"
	cellspacing="0"
	Headerstyle-BackColor="#8080C0"
	Headerstyle-Font-Name="Arial"
	Headerstyle-Font-Size="12"
        Headerstyle-Font-Bold="True"
	BackColor="#8080FF"
	Font-Name="Arial"
	Font-Size="11"
	BorderColor="Black"
	AutogenerateColumns="False"
	OnEditcommand="MyDataGrid_EditCommand"
	OnCancelcommand="MyDataGrid_Cancel"
	OnUpdateCommand="MyDataGrid_UpdateCommand">
	<Columns>
		<asp:EditCommandColumn
			ButtonType="LinkButton"
			UpdateText="Update"
			CancelText="Cancel"
			EditText="<IMG SRC=/images/Edit.gif Border=0 Width=12 Height=12>"
                                                ItemStyle-HorizontalAlign="Center"
		                HeaderText="Edit">
		</asp:EditCommandColumn>
		<asp:BoundColumn
			DataField="EmployeeID"
			HeaderText="EmployeeID"
			ReadOnly="True">
		</asp:BoundColumn>
		<asp:BoundColumn
			DataField="FirstName"
			HeaderText="FirstName">
		</asp:BoundColumn>
		<asp:BoundColumn
			DataField="LastName"
			HeaderText="LastName">
		</asp:BoundColumn>
		<asp:BoundColumn
			DataField="Title"
			HeaderText="Title">
		</asp:BoundColumn>
	</Columns>
</asp:DataGrid>
</form>
</div>
</body>
</html>

Inserting Record into Database

This sample uses ASP.Net 1.x – for a sample using ASP.Net 2.0 check out:
Inserting With a DetailsView

This code example actually shows three things. The first and main idea represented is how to insert a record into a database, based on form input. It is most likely the simplest method of doing this and includes form validation (Required Fields).

The second item this example shows is how to clear all the textboxes in a form, based on one of the Tips and Tricks from this web site.

The last thing is how to have three buttons in one form (the limit is only one form to a page), doing three different things. Two of the buttons have the ‘CausesValidation’ property set to false, so that when they are clicked, it won’t cause the ASP.Net validation controls to fire.

NOTE: The clear textboxes code example won’t work in this online example due to several items outside my control at this time – however, it will work by copying the code as is to your system.

To change this to work with a Stored Procedure, just change the SQL Statement to :
MySQL=”SProcName” – The Stored Procedure would actually be the SQL listed originally.
Then, after the Dim Cmd as New SQLCommand line, declare the type of command:
cmd.CommandType=CommandType.StoredProcedure
The only thing left is to create the parameters:
cmd.Parameters.Add(New SQLParameter(“@Fname”, frmFname.text))
cmd.Parameters.Add(New SQLParameter(“@Lname”, frmLname.text))

The rest is the same – that’s all there is to it!

Go to this sample done with an MS Access database

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<script language="VB" runat="server">

Sub doInsert(Source as Object, E as EventArgs)
	Dim MySQL as string = "Insert into testInsert (fname, lname) values (@Fname, @Lname)"
	Dim myConn As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("YourAppSettings"))
	Dim Cmd as New SQLCommand(MySQL, MyConn)
	cmd.Parameters.Add(New SQLParameter("@Fname", frmfname.text))
	cmd.Parameters.Add(New SQLParameter("@Lname", frmlname.text))
	MyConn.Open()
	cmd.ExecuteNonQuery
	label1.visible="true"
	BindData()
	MyConn.Close()
	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 SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("YourAppSettings"))
	Dim ds as DataSet=New DataSet()
	Dim Cmd as New SQLDataAdapter(MySQL,MyConn)
	Cmd.Fill(ds,"testInsert")
	MyDataGrid.Datasource=ds.Tables("testInsert").DefaultView
	MyDataGrid.DataBind()
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>

<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>

<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>
<asp:Label ID="label1"  runat="server" />

DataReader RowCount Check – Before Display

Sometimes, we’d like to know if there are actually records to be returned in our query. If there are no records, then, we could display a message accordingly. Otherwise, we can then display the record(s) as needed.

Using two reads of a DataReader, the following Code Sample demonstrates how to do this, using the Northwind Database (SQL Server)

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 2.1">
<title>DataReader Record Check</title>
<script language="VB" runat="server">
Dim strName as string
Sub searchit(Source as Object, E as EventArgs)
strName=text1.text
Dim strConn as string = "server=(local);uid=sa;pwd=PASSWORD;database=Northwind"
Dim sql as string = "Select FirstName, LastName, Title from NWEmployees where lastname=’" & strName & "’"
Dim conn as New SQLConnection(strConn)
Dim Cmd as New SQLCommand(sql, conn)
Dim objDR as SQLDataReader
conn.Open()
objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
if Not objDR.Read() then
Label1.text = "There are no employees with the name – " & strName & "."
objDR.Close
conn.Close
myDataList.visible="false"
label1.visible="true"
else
objDR.close
conn.Open
objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
MyDataList.datasource=objDR
MyDataList.Databind
myDataList.visible="true"
label1.visible="false"
End If
End Sub
</script>
</head>
<body>
<Form id="form1" runat="server">
Enter Last Name: <asp:TextBox id="text1" runat="server" /> <asp:Button id="button1" Text="Search" onclick="searchit" runat="server" /><br>
<font Size="2"><i>(Hint – Try ‘Davolio’, ‘Fuller’, ‘King’, ‘Peacock’ for valid names)</i></font>
<asp:DataList runat="server"
Id="MyDataList"
GridLines="Both"
cellpadding="2"
cellspacing="2"
Font-Name="Arial"
Font-Bold="false"
Font-Size="12"
Visible="false">
<ItemTemplate>
<b>Name: </b><%# Container.DataItem("FirstName")%>
<%# Container.DataItem("LastName")%><br>
<b>Title: </b><%# Container.DataItem("Title")%>
</ItemTemplate>
</ASP:DataList><br><asp:Label ID="label1" forecolor="red" font-Italic="true" runat="server" />
</Form>
</body>
</html>

Dynamically Loading User Controls

Sometimes, based on conditional statements, we may need to load one or more user controls, dynamically – like –
if condition #1 is true then
load control1
else
load control2
end if

This sample shows how to do this, based on three controls (First.ascx, Second.ascx, and Third.ascx)

The only code in each of theses User Control Files is in the following format:

<hr>
<div align=”center”><b><i>This is the First Control</i></b></div>
<hr>

Naturally, change the text for each User Control. Save each one with the file names above. Then, copy the code below to a new page. Also make note (from the code) that the files are in a directory called ‘aspnet’, off the root directory of your web site.

<html>
<head>
<meta name="GENERATOR" Content="ASP Express 2.1">
<title>Conditional Controls</title>
<script language="VB" runat="server">
Dim strLoad as string
Sub doit(Source as Object, E as EventArgs)
strLoad="/aspnet/" & rb1.selecteditem.text & ".ascx"
Dim myControl as Control=CType(Page.LoadControl(strLoad), Control)
ph1.Controls.Add(myControl)
End Sub
</script>

</head>
<body>
<Form id="form1" runat="server">
<asp:RadioButtonList id="rb1" runat="server">
<asp:listitem id="First" Value="First" runat="server"/>
<asp:listitem id="Second" Value="Second" runat="server"/>
<asp:listitem id="Third" Value="Third" runat="server"/>
</asp:RadioButtonList><br>
<asp:Button id="button1" Text="Load Controls" onclick="doit" runat="server" />
</Form>
<asp:placeholder ID="ph1" runat="server"></asp:placeholder>
</body>
</html>

Binding RadioButton List to DataSource

This code sample shows first, how to bind a RadioButtonList to a SQL Server DataSource. Then, once an item in the RadioButtonList is selected, a search is made from its DataValueField and returns a list of items matching its search criteria to a DataGrid.

As usual, this uses the SQL Server flavor of the Northwind database, so all you need to do to make this work at home is to copy the code to a new page and change the data connection properties.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 2.1">
<title>Untitled</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=YourServer;uid=UID;pwd=PWD;database=NorthWind"
Dim sql as string = "Select EmployeeID, FirstName + ‘ ‘ + LastName as Name from Employees"
Dim conn as New SQLConnection(strConn)
Dim objDR as SQLDataReader
Dim Cmd as New SQLCommand(sql, conn)
conn.Open()
objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
rb1.DataSource = objDR
rb1.datavaluefield="EmployeeID"
rb1.dataTextField="Name"
rb1.DataBind()
end if
End Sub

Sub doit(Source as Object, E as EventArgs)
Dim strConn as string = "server=YourServer;uid=UID;pwd=PWD;database=NorthWind"
Dim sql as string = "Select EmployeeID, FirstName + ‘ ‘ + LastName as Name, Title, BirthDate from Employees where EmployeeID=" & rb1.selecteditem.value
Dim conn as New SQLConnection(strConn)
Dim objDR as SQLDataReader
Dim Cmd as New SQLCommand(sql, conn)
conn.Open()
objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
MyDataGrid.DataSource = objDR
MyDataGrid.DataBind()
End Sub
</script>

</head>
<body>
<Form id="form1" runat="server">
<table> <tr>
<td align="Left" valign="Top">
<asp:RadioButtonList id="rb1" cellpadding="0" cellspacing="0" repeatdirection="vertical" runat="server" />
<asp:Button id="button1" Text="Get Item" onclick="doit" runat="server" />
</td>
<td align="Left" valign="Top">
<asp:Datagrid runat="server"
Id="MyDataGrid"
GridLines="Both"
cellpadding="0"
cellspacing="0"
Headerstyle-BackColor="#8080C0"
Headerstyle-Font-Name="Arial"
Headerstyle-Font-Size="12"
Headerstyle-Font-Bold="true"
BackColor="#8080FF"
Font-Name="Arial"
Font-Size="10"
BorderColor="Black"
AutogenerateColumns="False">
<Columns>
<asp:BoundColumn DataField="EmployeeID" SortExpression="EmployeeID" HeaderText="EmployeeID"></asp:BoundColumn>
<asp:BoundColumn DataField="Name" HeaderText="Name"></asp:BoundColumn>
<asp:BoundColumn DataField="Title" SortExpression="Title" HeaderText="Title"></asp:BoundColumn>
<asp:BoundColumn DataField="BirthDate" SortExpression="BirthDate" HeaderText="BirthDate"></asp:BoundColumn>
</Columns>
</asp:DataGrid>
</td>
</tr>
</table>
</Form>
</body>
</html>

Populating a Form's TextBoxes from a DB Query

At times, we need to populate TextBoxes in a Form with Data received from a query. This form data can then be used to update the table or pretty much anything else you wanted to do, at that point.

This sample uses the SQL Server flavor of the Northwind Databse to populate a listbox with the last names of employees (EmployeeID is the Value field for the listbox). Based on the selection from that Listbox, the user clicks the Edit Record button to populate the form fields. The Textbox population takes place by using Variables generated by a DataReader, much like in the Classic ASP days.

The Update button is for show only – no actual updating is covered in this sample.

To get this to work on your system, just copy the code below into a new page, change your connection string information.

To see a the second part of this sample, with full editing capabilities, go to:
Updating/Editing a Chosen DataBase Record

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 2.1">
<title>Untitled</title>
<script language="VB" runat="server">
Dim intWdth, intID as integer
Dim strFirst, strLast, strTitle as string
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
Dim strConn as string = "server=YourServer;uid=UID;pwd=PWD;database=Northwind"
Dim sql as string = "Select EmployeeID, FirstName, LastName from Employees"
Dim conn as New SQLConnection(strConn)
Dim Cmd as New SQLCommand(sql, conn)
Dim objDR as SQLDataReader
conn.Open()
objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
list1.datasource=objDR
list1.DataValueField="EmployeeID"
list1.datatextfield="LastName"
list1.databind
list1.selectedindex=0
conn.Close()
End If
End Sub

Sub EditRecord(Source as Object, E as EventArgs)
Dim strConn as string = "server=YourServer;uid=UID;pwd=PWD;database=Northwind"
Dim sql as string = "Select EmployeeID, FirstName, LastName, Title from Employees Where EmployeeID = " & list1.selecteditem.value
Dim conn as New SQLConnection(strConn)
Dim objDR as SQLDataReader
Dim Cmd as New SQLCommand(sql, conn)
conn.Open()
objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
While objDR.Read()
intID=objDR("EmployeeID")
strFirst=objDR("Firstname")
strLast=objDR("LastName")
strTitle=objDR("Title")
End While
page.databind()
label1.text=""
label2.text=""
End Sub

Sub doUpdate(Source as Object, E as EventArgs)
label1.text="Successfully updated — – "
label2.text="(There is no REAL update here – that will be left for another sample)"
‘ here, you would put your actual code to do whatever you need to, with the populated fields.
End Sub
</script>
</head>
<body>
<form Name="form1" runat="server">
<table border="1" width="100%"> <tr>
<td align="center"width="145" valign="Top"><b><i>Choose from List:</i></b><br>
<asp:ListBox id="list1" Width="125px" height="150px" runat="server" /><br>
<asp:button id="button1" Text="Edit Record" onclick="EditRecord" runat="server" />
</td>

<td align="Left" valign="Top"><b>ID : </b><%# intID %><br>
<b>FirstName : </b> <asp:textbox id="frmFirstName" Text="<%# strFirst %>" runat="server" /><br>
<b>LastName : </b><asp:textbox id="frmLastName" runat="server" Text="<%# strLast %>" /><br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>Title : </b><asp:textbox id="frmTitle" text="<%# strTitle %>" runat="server" /><br>
<br>
<asp:button id="button2" Text="Update" onclick="doupdate" runat="server" />
<i><asp:Label ID="label1" forecolor="red" runat="server" /></i><br>
<i><asp:Label ID="label2" runat="server" /></i>
</td>
</tr>
</table>
</form>
</body>
</html>

Inserting Item into DropDownList

Sometimes, it becomes necessary to add items into a DropDownList, after it is already filled at Page_Load. One of the most common questions concerning this, is how to add an item to the top of the list. Many times, it will just be adding a blank space, for which you could do this once the databind happens. This example shows how to add an item dynamically, based on input from a text box.
And, once again, as usual, this example uses the SQL Server flavor of the Northwind database/ the Employees table. To make this work on your computer, just copy and past the code into a new aspx page – then change the connection properties to suite your system.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 2.1">
<title>Untitled</title>
<script language="VB" runat="server">
Sub doit(Source as Object, E as EventArgs)
if text1.text<>"" then ddl.Items.Insert(0, new ListItem(text1.text))
ddl.selectedindex=0
End Sub
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
Dim strConn as string = "server=YourServer;uid=UID;pwd=PWD;database=NorthWind"
Dim sql as string = "Select LastName from Employees"
Dim conn as New SQLConnection(strConn)
Dim objDR as SQLDataReader
Dim Cmd as New SQLCommand(sql, conn)
conn.Open()
objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
ddl.DataSource = objDR
ddl.datatextfield="lastName"
ddl.DataBind()
end if
End Sub
</script>
</head>
<body>
<Form id="form1" runat="server"><b>Add Item here: </b>
<asp:TextBox id="text1" runat="server" /><br>
<asp:DropDownList id="ddl" runat="server" />
<asp:Button id="button1" Text="add item" onclick="doit" runat="server" />
</Form>
</body>
</html>

Show DB Tables in DropDownList – Select from Table

Sometimes, we have the need to merely look at the tables from a database, choosing the actual table dynamically. This example shows how to list the Table Names from a SQL Server, in a DropDownList, select from the list, and then shows the results of the table in a DataGrid. (Since these tables are not in separate db in this system, it will show up with ‘NW’ as a prefix to each tablename – naturally, I don’t want to show all of my tables :) .
For a reference, it uses the NorthWind database, so to use it on your page, just copy the code into a new page and change the connection properties.

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

<script language="VB" runat="server">
Dim sql as String
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
Dim strConn as string = "server=YourServer;uid=UID;pwd=PWD;database=Northwind"
sql = "SELECT [name] FROM sysobjects WHERE xtype=’U’ ORDER BY name"
Dim conn as New SQLConnection(strConn)
Dim Cmd as New SQLCommand(sql, conn)
conn.Open()
ddl.DataSource = Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
ddl.DataBind()
conn.Close
end if
label1.text=""
label1.text=sql
End Sub

Sub getstuff(Source as Object, E as EventArgs)
Dim strConn as string = "server=YourServer;uid=UID;pwd=PWD;database=Northwind"
sql = "Select * from [" & ddl.selecteditem.text & "]"
Dim conn as New SQLConnection(strConn)
Dim Cmd as New SQLCommand(sql, conn)
conn.Open()
MyDataGrid.DataSource = Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
MyDataGrid.DataBind()
conn.close
label1.text=""
label1.text=sql
End Sub
</script>

<Form id="form1" runat="server"> <div align="center"><asp:Label ID="label1" runat="server" /></div>
<br>
<asp:DropDownList id="ddl" datatextfield="name" runat="server" /> <asp:Button id="button1" Text="Get Stuff" onclick="getstuff" runat="server" />
<asp:Datagrid runat="server"
Id="MyDataGrid"
GridLines="Both"
cellpadding="0"
cellspacing="0"
width="100%"
Headerstyle-BackColor="#8080C0"
Headerstyle-Font-Name="Arial"
Headerstyle-Font-Bold="True"
Headerstyle-Font-Size="8"
BackColor="#8080FF"
Font-Name="Arial"
Font-Bold="True"
Font-Size="8"
BorderColor="Black">
</asp:DataGrid>
</Form>