Loop through all or certain type of controls on the ASP.NET Page

You can loop through all or certain type of controls on ASP.NET Page using this code. Code will loop through also those controls that are contained in some other container that Form, Panel for example.

Example of looping through all TextBoxes on Page.

[C#]
private void LoopTextBoxes (Control parent)
		{
			foreach (Control c in parent.Controls)
			{
				TextBox tb = c as TextBox;
				if (tb != null)
					//Do something with the TextBox

				if (c.HasControls())
					LoopTextBoxes(c);
			}
		}

And you can start the looping by calling:

LoopTextBoxes(Page);
[VB]
  Private Sub LoopTextBoxes(ByVal parent As Control)
        Dim c As Control
        For Each c In parent.Controls
            If c.GetType() Is GetType(TextBox) Then
                'Do something with the TextBox
            End If

            If c.HasControls Then
                LoopTextBoxes(c)
            End If
        Next
    End Sub

And in this case, start it by calling:

LoopTextBoxes(Me)

Membership/Roles with Remote DB

This will be a very short tutorial, actually. If you know how easy it is to create all the tables, and stored procedures with the ASP.Net Login controls, you know that it creates a database, by default, in the App_Data directory, called ASPNet.mdf. However, in the real world, that sometimes doesn’t cut it – especially if you have a hosted web site.

There are only two steps to get everything setup on any other SQL 2000 or SQL 2005 server. The first step is to use the ASPNet_regsql.exe application that comes with your installation. The hardest part about using this is that you will need to use the Command Prompt (Start/Run/cmd) and navigate to the correct directory/folder, which is:

C:\windows\Microsoft.net\Framework\

At the time of this writing, the version is v2.0.50727. When you get to the directory, type in:

aspnet_regsql -W

There are a lot of other registration options that are possible, but this will get you to the GUI to handle this, instead of having to learn what all the options might or might not mean to you. The rest is no more difficult than entering the IP address of your SQL Server, the user ID and the Password. Just follow the wizard all the way through this, and it will setup all the Tables and Stored Procedures you need to handle this.

The last and second step is to create a ConnectionString entry in the ConnectionString section of your web.config for your application, using ‘LocalSQLServer’ as the name:

<connectionStrings> <remove name="LocalSqlServer" /> <add name="LocalSqlServer" connectionString="server=YourSrvr;uid=YourUID;pwd=YourPWD;database=YourDB" providerName="System.Data.SqlClient" /> </connectionStrings>

As you probably noticed, there is a line above the connectionString, with ‘remove LocalSQLServer’. If you already have created a connection to the default server, this may be in the Machine.config file already. This makes sure the one you want is used. It removes it from memory, if it’s there, and then adds your particular server back.

Then, the last step is to add a Membership/Provider section to the Web.Config to tie it all together:
Continues…

3 Ways to Display a Dataset in a Web Page

When we first start using ASP.Net, many people first start working with a DataGrid due to its apparent ‘on the surface’ simplicity. Of course as learning progresses, we find out just how powerful it really is. Also, we learn about the DataSet and how to make it the DataSource of the DataGrid. However, many times, other methods of displaying the results in the DataSet are overlooked even though the DataGrid is not exactly what’s needed.

This code sample uses the SQL Managed Provider (Employees table in the Northwind database) to show 2 other ways to display the results from a DataSet (a DataList and assigning the data to a variable then, using a server control’s text property to display the records however we need.

To use this on your local computer, just copy the code below to a new page on your system. Then, change the connection string to your database. If you are using MS Access, just copy the code to the DataBase Code Conversion Tool on this web site.

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

<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.2">
	<title>3 Ways to Display a DataSet</title>
<script language="VB" runat="server">
Dim sEmps as String
Dim strConn as string = "server=YourServer;uid=YourUID;pwd=YourPWD;database=NorthWind"
Sub Page_Load(Source as Object, E as EventArgs)
	Dim MySQL as string = "Select Employees.FirstName, Employees.LastName, Employees.Title, " & _
	"Employees.BirthDate from Employees"
	Dim MyConn as New SQLConnection(strConn)
	Dim ds as DataSet=New DataSet()
	Dim Cmd as New SQLDataAdapter(MySQL,MyConn)
	Cmd.Fill(ds,"Employees")

	''These next 2 lines assign the data in the dataset to the Datalist (MyDataList)
	MyDataList.Datasource=ds.Tables("Employees").DefaultView
	MyDataList.DataBind()

	''These lines assign the data to a variable, which is then assigned to the text property of a literal control(litEmps)
	Dim dr As DataRow
	For Each dr In ds.Tables("Employees").Rows
		sEmps+="<b>" & dr("firstname") & " " & dr("lastname") & " </b> - " & dr("Title") & "<br>"
	Next
	litEmps.text=sEmps

	''then, here we assign the data to a DataGrid, much like the way we did in the example for the DataList:
	MyDataGrid.Datasource=ds.Tables("Employees").DefaultView
	MyDataGrid.DataBind()
End Sub
</script>
</head>
<body>

<Form id="form1" runat="server">
<div align="center"><table>	<tr>
		<td align="Left" valign="Top"><b><i><font Color="#0000FF">Using a DataList:</font></i></b>
	<asp:DataList runat="server"
		Id="MyDataList"
		GridLines="None"
		cellpadding="2"
		cellspacing="2"
		Headerstyle-BackColor="#8080C0"
		Headerstyle-Font-Name="Arial"
		Headerstyle-Font-Size="8"
		Font-Name="Arial"
		Font-Bold="false"
		Font-Size="8">
		<ItemTemplate>
		<%# DataBinder.Eval(Container.DataItem, "firstname") %>
		<%# DataBinder.Eval(Container.DataItem, "lastname") %>
		 - <b><i><%# DataBinder.Eval(Container.DataItem, "Title") %> </i></b>
	</ItemTemplate>
	</ASP:DataList>
		</td>
		<td align="Left" valign="Top"><b><i><font Color="#0000FF">Using a variable:</font></i></b><br>
<asp:Literal ID="litEmps" runat="server"></asp:literal></td>
	</tr>
	<tr>
		<td align="center" valign="Top" Colspan="2"><hr>
	<b><i><font Color="#0000FF">Using a DataGid:</font></i></b>
	<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"
		AlternatingItemStyle-BackColor="#CFCFCF"
		AlternatingItemStyle-Font-Name="Arial"
		AlternatingItemStyle-Font-Size="8"
		BorderColor="Black">
	</asp:DataGrid>
		</td>
	</tr>
</table></div>
</Form>
</body>
</html>

Conditional Javascript – Setting Javascript Focus – Inline Coding

One of the ‘gotchas’ about inline coding is that, within a script tag, you can not have another script tag. On the surface that sounds reasonable.

However, let’s say, you have some conditional coding, in within that coding, you want to place focus in another textbox, using Javascript. Normally, you’d probably do something like this:
response.write(“<script>document.form1.txtLname.focus();</script>”)

The problem occurs when ASP.Net reads that closing script tag. It reads it as the close of it’s main Script tag.

To get around this and not confuse ASP.Net, you can do it like this:
response.Write (“<” & “script>document.form1.txtLoanNum.focus();<” & “/script>”)

Multiple DropdownLists with AppendDataBoundItems

With ASP.Net 2.0, using multiple DropdownLists is really simple. However, what happens when you want to add an extra item to the first DDL, like ‘ALL’?
Consider this scenario: You want all models (in this sample) returned, when the ‘All’ item is chosen.
You can’t put 2 SelectCommands in one DataSource control, but, when ‘All’ is selected, you still need the SQL statement (in this case, the DataSource Control’s ‘SelectCommand’ property) to change.

But, with just a little code, this is still fairly easy to accomplish. To do this, in this scenario, we’ll need two DropDownLists – one for the ‘Brands’ of automobiles, and one for the ‘Models’ of the particular brands. First, you create a new sub (here, it’s named ‘doCheck’, but you can call it anything you want), and add the following code:

Sub doCheck(Source as Object, E as EventArgs) if ddlBrand.SelectedItem.Value=99 then ds2.selectCommand="Select id, model from Models order by model" End If End Sub

Then, reference that subroutine in the DropDownList’s tag:

<asp:DropDownList id="ddlBrand" DataTextField="Brand" DataValueField="id" DataSourceID="DS1" AppendDataBoundItems="True" Runat="server" AutoPostBack="True" OnSelectedIndexChanged="doCheck" <asp:ListItem Value="99">All</asp:ListItem> </asp:DropDownList>

The ‘AppendDataBoundItems’ property is added, along with the ListItem, containing a value, so that the ‘All’ entry gets added to the DDL along with all the items returned from the Database. Keep in mind, the ‘All item was appended here, with a value of 99. There’s nothing magical about that number. It simply must be a number higher than anything the DDL’s databound value will return.

Next, we’ll create the second DropDownList (for the models table):

<asp:DropDownList id="ddlModels" DataTextField="Model" DataValueField="id" DataSourceID="DS2" Runat="server"> </asp:DropDownList>

Notice that each one of the DDLs reference it’s own DataSource control (DS1, and DS2). So, let’s create them here:
Continues…

Populating/Binding a DataList with a DataReader

This code sample uses the SQL Server Managed Provider to bind a DataList with a DataReader, showing only certain columns/fields from the table. It uses the Employees table of the Northwind Database. Also, it shows how you can use the Repeatcolumns property and Templates (both Header and Item Templates) to format the data on the page and block or show certain fields in the table.

To use this on your system, all you need to do is copy the code directly to a new page and change the connection string to match your needs on your system. Also, if you have MS Access, instead of SQL Server, be sure to visit our DataBase Code Conversion Tool to convert the SQL Server items to OleDb.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.2">
	<title>Populating a DataList with a DataReader</title>
<script language="VB" runat="server">
Dim strConn as String
Sub Page_Load(Source as Object, E as EventArgs)
	strConn  = "server=YourServer;uid=YourUID;pwd=YourPWD;database=YourDB"
	Dim MySQL as string = "Select FirstName, LastName, Title, BirthDate from Employees Order by LastName"
	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)
	MyDataList.DataSource = objDR
	MyDataList.DataBind()
End Sub
</script>
</head>
<body>
<Form id="form1" runat="server">
<asp:DataList runat="server"
	Id="MyDataList"
	GridLines="None"
	cellpadding="2"
	cellspacing="2"
	Font-Name="Arial"
	Headerstyle-BackColor="#E0E0E0"
	Headerstyle-Font-Name="Arial"
	Headerstyle-Font-Bold="True"
	Headerstyle-Font-Size="14"
	Headerstyle-HorizontalAlign="Center"
	Font-Size="10"
	RepeatColumns="3"
	Width="100%">
	<HeaderTemplate>
Employee Names/Birthdates
	</HeaderTemplate>
	<ItemTemplate>
		<b>Name: </b><%# Container.DataItem("FirstName")%> <%# Container.DataItem("LastName")%><br>
		<b>Title: </b><%# Container.DataItem("Title")%><br>
		<b>BirthDate: </b><%# formatdatetime(Container.DataItem("BirthDate"),vbshortdate)%><p>
	</ItemTemplate>
</ASP:DataList>
</Form>
</body>
</html>

Logic Driven MetaTags

Let’s say you have some sort of ‘Stats’ page and that users need to log into it. Let’s also say that you want it to use the REFRESH Meta Tag, once they’re logged in, with all the ‘parts’ of this in one page.

Since you don’t want the login part of the form refreshing all the time, what you can do is put your Meta Tag inside an ASP Literal Control.

Once your logic has been established for whether or not you want the meta tag to be available (maybe by creating uid/pwd sessions), then make the literal control ‘Visible’.

In the Page_PreRender Event, then include logic like this:

Sub Page_PreRender(Source as Object, E as EventArgs)
if session("uid")="" and session("pwd")="" then
	literal1.visible="false"
else
	literal1.visible="True"
End If
End Sub

Creating a Popup Details Page

Here’s the scenario – you have an order page, to view the details of specific orders. Now, from that order page, you’d like to see the details of the customer who made the order, but you don’t want to leave the order page behind.

The answer is a popup page. I know many people do not like popup pages, but for specific purposes, like this one, they can be very useful. To implement this scenario, first, let’s put a label on the page, for the Customer Name:

<asp:Label ID="lblCustName" Runat="server" />

Now, create a function to return a link to the page:

Function ShowCustName(sName as String, CustNum as String) if sName<>"" then Return "<a language=""Javascript"" href=""#"" onClick=""window.open('CustInfo.aspx?custnum=" & _ CustNum & "','Cust_Info', 'scrollbars=1,resizable,width=350, height=450');return false;""><b>" & sName & "</b></a>" end if End Function

What this function does, is to create a hyperlink to a second page (“CustInfo.aspx”), which will be the popup page, using the Customer # and the Customer name as arguments. The Customer name is only used, however, for the display part of the hyperlink.

The customer number (the value of which is assigned to a variable called pgCustNum), then, is used in the query string, to retrieve the customer details on the second page.

In the Page_Load event of the first page, we’re assuming that there will be a function or query to load all the order information for a specific order, which will include the customer number and name. We won’t go into that, because, that information will look different for each and everyone’s specfic order. However, just after retrieving the order information, we’ll populate the ‘lblCustName‘ label with the function:

lblCustName.text=ShowCustName(CustName, pgCustNum)

Lastly, on the second page, we will retrieve the Customer information. Again, we will not go into the formatting of this information on the page, since you can display this information however you’d wish. But – since this second page (CustInfo.aspx) came from a hyperlink, using a querystring, here’s how we can use it to retrieve the customer’s information.
Continues…

Enhanced DataBase Linked Calendar

This is an enhanced version of the other code sample showing how to do basic linking between a calendar and a database. In this example, we add one more field (Title) to the database table, which will then be shown in the appropriate day on the calendar. Also, this sample shows several other properties available to the Calendar control.

Again, we use the SQL Server Managed Provider for this example. The Table used is called CalSchedule, and the columns/fields are
ID (identity), CalDate (DateTime), Schedule(Text), and Title(varchar/50).
If you were using the OleDb Managed Provider, you would use:
ID (autonumber), CalDate (DateTime), Schedule(Memo), and Title(text).
(Data entered online will default to ‘Test Data’ for the Title).

To see an OleDb version of this code, to work with MS Access, click here.

Calculating Age

Try
Dim dbdate As String = "25 April 1976"
Dim newdate As DateTime = Convert.ToDateTime(dbdate)
Response.Write(newdate.ToString("d") & "<br>")
Response.Write("Age : " & DateDiff("yyyy", newdate, Now()))
Catch ex As Exception
Response.Write(ex.Message.ToString)
End Try