ASP.NET 101

ASP.NET and MVC Tutorials

Main menu

Skip to primary content
Skip to secondary content
  • Home
  • .NET Code Snippets
  • About
  • ASP.NET Books
  • ASP.NET FAQ's
    • ASP.NET Application State and Application Variables
    • ASP.NET Control State vs View State
    • How To Encrypt Connection Strings in ASP.NET
    • How to Find Out What Account ASP.NET is Running Under
    • How to Have Multiple Forms on an ASP.NET Page
    • How to Protect Against SQL Injection Attacks in ASP.NET
    • Set or Increase the Session Timeout in ASP.NET
    • ViewState vs Session State
    • What are the differences between System.Net.Mail and System.Web.Mail
    • What is WCF ?
  • ASP.NET Hosting
  • ASP.NET Resources
  • Featured Training
  • How to customize password generation in ASP.NET
  • Register
  • Register
  • Sample Page
  • Sample Page

Monthly Archives: September 2007

Post navigation

← Older posts

Compilation Error – (Control) is not a member of (Page)

Posted on September 27, 2007 by admin
Reply

If you get this error – you probably either have a server control, or a Script Tag that needs the ‘Runat=”Server”‘ designation added.ng weight by dancing videopersonal trainers costherb natural quit smokingdeviance in the eyes of functionalistscheated boyfriends vengeance photosoccupations use morse codebiblio com partners and affiliated companiesmensa genius iq testabilities of a psychicpast life regressions louisianacollin wayne dexter date of deathkidney to lung cancer

Posted in Tips | Leave a reply

Function Libraries

Posted on September 27, 2007 by admin
Reply

Remember the old days of Classic ASP, when you could have one file, included on each page, which housed all your common functions? Well, it’s still possible today. But, instead of having an ‘Include’ file, today, in ASP.Net, you can create a Function Library, all in one file. Yes, includes are still possible in ASP.Net, in fact, simple, headers and footers are still a good a very clean and efficient way, in my opinion, to handle these. But, when it comes to common functions, referencing a Function Library on each page is the way to go.

Let’s start out by creating a clean, new file (save with .cs or .vb). Since this is a VB.Net example, we’ll call it ‘LIB.vb’. First, let’s Import a few namespaces (you’ll want to import whichever ones fit your needs). In our case, we’ll need these :

Imports System.Data Imports System.Data.SqlClient Imports System.Web.UI Imports System.Web.UI.WebControls

Then, let’s create our own Namespace, called ‘ASPNet101:

NameSpace ASPNet101 End Namespace

Inside that new namespace, on that page, we’ll create a new Class:

Public Class LB End Class

Now, let’s create several variables, inside that class that we’ll need to use:

Public Shared strConn as string = "server=YourServer;uid=YourUID;pwd=YourPWD;database=Your_DB" Public Shared MyConn as New SQLConnection(strConn) Public Shared MySQL as String Public Shared objDR as SqlDataReader

Now, since this a common function repository, we’ll include one function, to start out with, called ‘FillListBox’, and we’ll give it several arguments (Listbox, TblName, TblField, and TblID:

Public Shared Function FillListBox(LBName as ListBox, TblName as String, TblField as String, TblID as String) MySQL = "Select " & TblField & ", " & TblID & " from " & TblName MyConn.Open() Dim Cmd as New SQLCommand(MySQL, MyConn) objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection) lbName.DataSource = objDR lbName.DataTextField=TblField lbName.DataValueField=TblID lbName.DataBind() MyConn.Close() End Function

Click here, to see everything we have so far. Now, you’re probably asking, “But, how do I use it in my web page?” That’s no problem. In fact, that’s all that’s left to do in this tutorial. First, at the top of the page, let’s reference the ‘.vb’ file we just created:

<%@ Import Namespace="ASPNet101" %> <%@ Assembly src="LIB.vb" %>

Let’s create a Listbox on the page first, called ‘Listbox1′. Then, in the code section, we’ll reference populate the listbox with the Category Names from the Categories Table in the Northwind Database, using the code in the .vb file:
Continues…

Pages: 1 2
Posted in Tutorials | Leave a reply

Populating a DropDownList from a RadioButtonList

Posted on September 27, 2007 by admin
Reply

This sample uses the SQL Managed Provider and the Northwind Database to do the following:
Populate a RadioButtonList with the Category Names (using the CategoryID as the value field)

Then, based on the selection from the RadioButtonList, a DropDownList is populated with all the Product Names that fall in the selected Category.

Just copy the code into new page on your site and change the connection information.

Thanks to Joseph Janick for this next suggestion – he wanted to know how to make it work without the ‘Get Products’ button. It’s much simpler than most would think. Since the population of the DropDownList is being done in the ‘popddl’ Subroutine, after removing the button from the form, only two sections need to be added. In the RadioButtonList control itself, in the HTML, add these two items:
onselectedindexchanged=”popdll”
and
autopostback=”true”

The AutoPostback Property, being set to ‘True’, takes the place of the button. When you click on the RadioButtonList item, this tells it to automatically postback and run the sub or function designated in the onselectedindexchanged method.

It couldn’t get any simpler than that!

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.1">
	<title>Populating a DropDownList from a RadioButtonList</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=YourUID;pwd=YourPWD;database=Northwind"
	Dim MySQL as string = "Select CategoryID, CategoryName from NWCategories"
	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)
	rb1.DataSource = objDR
	rb1.DataBind()
end if
End Sub
Sub popddl(Source as Object, E as EventArgs)
	Dim strConn as string = "server=YourServer;uid=YourUID;pwd=YourPWD;database=Northwind"
	Dim MySQL as string = "Select ProductName from NWProducts Where CategoryID = @CatID"
	Dim MyConn as New SQLConnection(strConn)
	Dim objDR as SQLDataReader
	Dim Cmd as New SQLCommand(MySQL, MyConn)
	cmd.parameters.add(New SQLParameter("@CatID", rb1.selecteditem.value))
	MyConn.Open()
	objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
	ddl.DataSource = objDR
	ddl.DataBind()
	ddl.visible="true"
	lblProduct.text="Products in " & rb1.selecteditem.text & " Category"
	label1.text= ("Selected Value = " & rb1.selecteditem.value )
End Sub
</script>

</head>
<body>
<Form id="form1" runat="server">

<table border="0">	<tr>
		<td align="Left" valign="Top"><b><i>Categories:</i></b><br>
		<asp:RadioButtonList id="rb1" datatextfield="CategoryName" datavaluefield="CategoryID" runat="server">
		</asp:RadioButtonList> <asp:Button id="button1" Text="Get Products" onclick="popddl" runat="server" />
		</td>

		<td align="Left" valign="Top"><b><i><asp:Label ID="lblProduct"  runat="server" /></i></b><br>
		<asp:DropDownList id="ddl" datatextfield="Productname" visible="false" runat="server" /></td>
	</tr>
</table>

</Form>
<asp:Label ID="label1"  runat="server" />
</body>
Posted in Code Samples | Leave a reply

How to open a new web page with a button click

Posted on September 22, 2007 by admin
Reply

You can use Javascript to do so.
e.g.
<input type=”Button” Value=”Open New” onclick=”Javascript:window.open(‘webform1.aspx’);”>

Posted in Tips | Leave a reply

An Introduction to Validation Controls – Part I

Posted on September 22, 2007 by admin
Reply

XXXXXXXX

Posted in Tutorials | Leave a reply

Filling an ArrayList from a Database Table

Posted on September 22, 2007 by admin
Reply

Some ASP.Net server controls do not have a sort property, among other things that might be needed. Therefore, it becomes necessary to use an ArrayList, or the like, so that you can work with the ArrayList itself and then bind it to the server control, like a DropDownList, which is used in this sample.

This is a very simple example of reading through the records of a table, using SQL Server and the Northwind Database (Categories table), adding the items to the ArrayList, and then, binding the ArrayList to the DropDownList

<%@ 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 MyArrayList as ArrayList
Dim sItem as String
Sub Page_Load(Source as Object, E as EventArgs)
MyArrayList=New Arraylist
if not Page.IsPostBack then
Dim strConn as string = "server=YourServer;uid=UID;pwd=PWD;database=NorthWind"
	Dim MySQL as string = "Select CategoryName from Categories"
	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)
	While objDR.Read()
		MyArrayList.add(objDR("CategoryName"))
	End While
end if
ddl1.datasource=MyArrayList
ddl1.databind
End Sub
</script>
</head>
<body>

<Form id="form1" runat="server">
<asp:DropDownList id="ddl1" runat="server" />
</Form>
</body>
</html>
Posted in Code Samples | Leave a reply

QuickStart Tutorials/Class Browser Locally

Posted on September 17, 2007 by admin
Reply

You may not know this, but when you install the framework, the QuickStart Tutorials, along with the great Class Browser Application, are on your computer and can be accessed through your localhost.

Navigate through your file system to:
C:\Program Files\Microsoft Visual Studio .NET\FrameworkSDK\Samples\StartSamples.htm
or, for v1.1 –
C:\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\Samples\startsamples.htm

Assuming you already have either MSDE or SQL Server installed on your computer, just click the link at
Step 2: Set up the QuickStarts

Then – anytime you want to access the QuickStarts – just go to:
http://localhost/quickstart/default.aspx

Posted in Tips | Leave a reply

Sending Mass Emails Part 2

Posted on September 17, 2007 by admin
Reply

If you haven’t read Part 1 in this series, you can do so now, by clicking here:

Sending Multiple Emails At Once

One of the major drawbacks of creating a mass emailing like we did in Part 1, was personalization and customization were practically non-existent. All email addresses were kept in a string, which populated the BCC section. Each recipient could easily see that this was a mass email. Naturally, that’s normally OK, but by being able to personalize an email gives the recipient a better feeling when he things that the ‘Sender’ of the email took the time to send the email to him, personally. By building your mass email this way, practically any level of personalization and customization is all up to you. For instance, you could create a link in the email itself, that, when clicked, can run a script on your web site to delete that user from the email list automatically.

For this example, all you’ll really need is:

  1. Import the System.Web.Mail namespace
  2. Import the Database namespaces necessary
  3. A table of Data, in the Database (for this sample, we only have two fields (Name and Email)
  4. One subroutine for the code (for this example, we’ll use Page_Load)
  5. A label with an ID of ‘lblEmails’ (only to show the list of emails for the test)

First, we’ll Import the namespaces. For emailing, we must add:

<%@ Import Namespace="System.Web.Mail" %>

For the database (we’re using SQL Server for this tutorial), we must add:

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

Now, for the real ‘meat’ of this tutorial, first, we’ll add two Global variables:

Dim sEmail as String Dim sBody as String

Next, in a Subroutine of your choice, add this code:
Continues…

Pages: 1 2
Posted in Tutorials | Leave a reply

Getting Record Count with a DataReader

Posted on September 17, 2007 by admin
Reply

This code sample uses the Northwind.mdb database (OleDb) to show how to get a recordcount returned, using a DataReader. There is no where clause with this sample, since it allows the end user to select the table for the count, but works equally as well with a where clause.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDB" %>
<html>
<head>
	<meta name="GENERATOR" Content="ASP Express 2.1">
	<title>Untitled</title>
<script language="VB" runat="server">
Dim intNum as Integer
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
	ddl.items.add("Products")
	ddl.items.add ("Customers")
	ddl.items.add ("Categories")
	ddl.items.add("Employees")
end if
End Sub
Sub doCount(Source as Object, E as EventArgs)

Dim MySQL as string = "Select * from " & ddl.selecteditem.text

Dim strConn as string = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & server.mappath("\data\northwind.MDB") & ";"
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)
intNum=0
While objDR.Read()
  intNum = intNum+1
End While
label1.text= ("<b><i><font Color=""#8000FF"">Number of Records in " & ddl.selecteditem.text & "Table</font></i> : </b>" & intNum)
End Sub
</script>
</head>
<body>
<Form id="PutIDNameHere" runat="server">
<asp:DropDownList id="ddl" runat="server" /><asp:Button id="button1" Text="Get Count" onclick="docount" runat="server" />
</Form>
<asp:Label ID="label1"  runat="server" />
</body>
</html>
Posted in Code Samples | Leave a reply

Beginners Guide to Forms Authentication in ASP.NET

Posted on September 12, 2007 by admin
Reply

There are four basic parts to simple forms authentication. Those parts are:

  1. The form (to gather user ID & pwd) itself
  2. The Web.Config File entry
  3. The Data Store (the place where you keep the usernames and passwords
  4. The Validation Process, triggered in the click event of the form.

Here is an example of the simplest of Forms (let’s call the page ‘Login.aspx’), designed to gather the user ID and password:

<table> <tr> <td align="Right" valign="Top"><b>User ID: </b></td> <td align="Left" valign="Top"> <asp:TextBox id="txtUID" Runat="server" /> </td> </tr> <tr> <td align="Right" valign="Top"><b>Password: </b></td> <td align="Left" valign="Top"> <asp:TextBox id="txtPWD" TextMode="Password" Runat="server" /> </td> </tr> <tr> <td align="Right" valign="Top" Colspan="2"> <asp:Button id="submitButton" Text="Login" onclick="doLogin" Runat="server" /> </td> </tr> </table>

In the Web.Config file, add this:

<authentication mode="Forms"> <forms name=".FormName" loginUrl="login.aspx" ' remember how we named the page for the form? protection="All" timeout="480" path="/" /> </authentication> <authorization> <deny users ="?" /> </authorization>

For the DataStore – you can use anything you’d like – however, I’m a bit partial to databases for quick interaction, so this example will be using a database. You’ll need to create a table in your database to store your names, User ID and Passwords. Here’s a list of the basic table fields you’ll need:

Field Name DataType Notes
id Integer (for Access, use AutoNumber; for SQL Server, create Identity)
Name MS Access: Text; SQL Server: VarChar use a length you feel is appropriate
- you can also make this two fields (First and Last names) to be able to more easily use their first name other places on the site, once they’re logged in
Login MS Access: Text; SQL Server: Varchar, unless you want an exact number of characters.
Password (same as above)

For the actual work to do this, create a click event for the button in the form. Let’s call it ‘doLogin’. Also, you’ll create a Function to do the validation – - let’s call it ‘ValidateUser’, with a couple of arguments, ‘uid‘ and ‘pwd‘. Also, create a label with an ID of ‘lblError’, just in case the login attempt fails.
Continues…

Pages: 1 2
Posted in Tutorials | Tagged Authentication | Leave a reply

Post navigation

← Older posts

newsletters

  • Finance Newsletter
  • I.T. Newsletter
  • WordPress Newsletter
Proudly powered by WordPress