A Beginners Guide to the Connection String

One of the most misunderstood items, using ASP.Net, and some of the most asked questions, are about Connection Strings – the way in which you connect to the database. Any time you connect to a database, a Connection String is required, so it’s an integral part of .Net programming, whether it’s ASP.Net or WinForms programming. Of course, here, we’re addressing only ASP.Net programming, and mainly with SQL Server.

Each Connection String has several ‘sections’ in it. The basic form of the Connection String consists of:

ConnectionString=""

Your string can reside in different locations, including a DataSource Control (ASP.Net 2.0), in code, on the fly, and in the Web.Config file. Most likely, if you are using a particular string in multiple locations throughout your website, it will probably be best to store it in the Web.Config file. Then, any time, in your application, you need the connection string, the setting in the Web.Config file is referenced instead of the exact connection string. This way, if the connection string ever changes (and believe me, after years of doing this, I’m here to attest that it most likely WILL change at some time), then you will only need to change it in one place. How this is done, will be addressed, later on in this tutorial,

There are many sections of a connection string which are possible, but there are 3 basic sections which are absolutely required: The Server
The Database Name
The authentication

The Server can be notated in the Connection String several different ways, however, the most common usages are:

Data Source=YourServerGoesHere Server=YourServerGoesHere

In the above section, instead of ‘YourServerGoesHere’, you would put the address to the Server itself, in either a domain type of construction (like:MyServer.Com), or an IP address (like: 198.12.1987).

So, at this point, using the Basic form from above, this would look like:

ConnectionString="Data Source=YourServerGoesHere" or ConnectionString="Data Source=YourServerGoesHere"

Naturally, the above, as mentioned before, can use ‘Server’ instead of ‘Data Source’

Next comes the Database section. It may be in 2 different forms:

Database=Northwind Intial Catalog=Northwind

The different sections in the Connection String need to be separated, so in order to do this, we use a semi-colon in between the different sections “;”. The entire connection string, then, will be surrounded by double-quotes

At this point, using the Basic form from above, this would look like:
Continues…

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…

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…

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…

Beginners Guide to the BulletedList

The BulletedList is an ASP.net server control which is new, with v2.0 of ASP.Net. At first glance, you might think that, being a way to use a database to populate an HTML select list is a really nice feature. However, if that’s all there was too it, you’d be correct, but the feature list is really nice!

First off, let’s start with the data binding features. Naturally, as you’d expect with a v2.0 control, the DataSourceID can be used to populate the list, along with DataTextField and DataValueField properties for populating the Text and Values of each list item.

Now, let’s couple that with the DisplayMode property. There are three modes:

  • HyperLink
  • LinkButton
  • Text (default)

First, let’s look at the Hyperlink mode. It can be used with either Databound or non-DataBound BulletedLists. When using a Databound BulletedList, the DataValueField can be populated with the actual URL, while any text field can be used for populating the DataTextField. If the BulletedList is non-DataBound, the actual URL can be added to the ‘Value’ attribute of each ListItem.

Also, the Linkbutton mode can be used to fire off a subroutine or function to do just about anything within the confines of ASP.net. Using code, or another DataSourceID, by choosing an item in the BulletedList to trigger that code. For instance, the display text of each item can be used in a SQL statement’s ‘Where’ clause, or any other use which uses the text or value of the selected list item. In the BulletedList tag, the OnClick event is used:

<asp:BulletedList ID="BL1" Runat="Server" OnClick="Choose_Item" />

Then, the actual code is placed in a subroutine, somewhat like this:

Sub Choose_Item (Src As Object, e As BulletedListEventArgs) dim MySQL as String="Select (FieldList) from (TableName) where (FieldName)='" & _ BL1.Items(e.Index) & "'" ' Rest of code or DataSource SelectCommand assignment goes here End Sub

There are 8 different style which can be used with the BulletedStyle property, which are, for the most part, fairly self-explanatory:
Continues…

Emailing Form Results with ASP.Net 2.0

The task at hand is taking the input from a form, and emailing those results to a desired target. If you’ve worked with ASP.Net v1.1, things have changed a little. Please check out the basic email precepts in this tutorial. Even if you are new to programming, you’re going to be amazed at how simple this really is. This is an updated/revamped Tutorial, based on the same scenario as a previous tutorial, using ASP.Net v1.1.

The first thing that’s necessary, of course is the form. For this example, we’re using VB.Net and ASP.Net server controls. Naturally, for the purposes of this tutorial, we’re going to keep it fairly simple, but the same principles apply for a much more expanded form. Here’s a sample of the HTML section for the form:

<Form id="form1" runat="server">
First Name: <asp:TextBox id="txtFname" runat="server" />
Last Name: <asp:TextBox id="txtLname" runat="server" />
Email: <asp:TextBox id="txtEmail" runat="server" />
CC: <asp:TextBox id="txtCC" Runat="server" />
<br />Favorite Color: <asp:DropDownList id="ddlColor" Runat="server">
<asp:ListItem>Blue</asp:ListItem>
<asp:ListItem>Red</asp:ListItem>
</asp:DropDownList><br />
<asp:Button id="btnEmail" Text="Email Form" onclick="doEmail" runat="server" />
</Form>

The next thing to make sure we have listed on our page is a reference to the correct namespace. For emailing, it’s:

<%@ Import Namespace=”System.Net.Mail” %>

As you probably noticed, there is an ‘onclick’ event referenced for the form’s button, ‘doEmail‘. This is where we’ll take the output of the form and do the actual emailing of the input.

Sub doEmail(Source as Object, E as EventArgs)
	Dim sMsg as String
	sMsg+="Hi there - here's the information I entered in the form." & vbcrlf
	sMsg+="First Name : " & txtFname.Text & vbcrlf
	sMsg+="Last Name : " & txtLname.Text & vbcrlf
	sMsg+="Favorite Color: " & ddlColor.SelectedItem.Text

	Dim Msg as MailMessage = new MailMessage()
	Dim MailObj As New SmtpClient("mail.YourDomain.com")
	Msg.To.Add(new MailAddress(txtEmail.text)
	Msg.CC.Add(new MailAddress(txtCC.text)
	Msg.BCC="JohnnyWhite@jwmason.com"   '<- - - you can send it to yourself at the same time.
	Msg.From = new MailAddress("me@Here.com", "Big D")

	Msg.Subject="Here's the subject of the email"
	Msg.Body=sMsg
	Msg.IsBodyHtml = "False"
	MailObj.SmtpServer ="mail.Wherever.com"   < - - check with your hosting provider on what to put in here
	MailObj.Send(Msg)

End Sub

In this sub, you’ll notice that the first thing we’re doing is creating a string variable to store our email message. The first part of the message is the opening line, but then you’ll see we’re adding and formatting the specific data from the form, item by item. Naturally, that can be formatted pretty much most anyway you’d like.
Continues…

Using TemplateFields in ASP.NET

If you’ve been developing with ASP.Net for a while, you probably are at least thinking ‘TemplateFields‘ sound familiar. That’s because in other controls (v1.1 era), we had ‘TemplateColumns‘. TemplateFields are and do the same general things in newer v2.0 controls, like the GridView, DetailsView and FormsView.

Like the subtitle says, if you haven’t used them yet, you will, sooner or later, so you might as well learn about them now.

Everyone knows that, using the BoundFields (BouldColumns with the DataGrid) are very powerful, however, if you haven’t found out yet, you will eventually find out that BoundFields don’t exactly fit for every purpose in ASP.Net. We’ll present only two scenarios here, one with a GridView and one with a DetailsView control. The first one, with the GridView control will inlcude a ‘State’ field in the database table. Now, for pure data display, a BoundField fits the job perfectly, but if you need to edit the data, would you rather trust the end user to type in the exact two letter state code every time, or would you rather have a DropDownList, which allows the user to choose from a finite list?

Naturally, the latter solution would be better. Here, we can populate the DropDownList with only those State codes that you or your company actually deal with, either manually, with a User Control, or populate it from a database. Whichever way you choose, will still entail creating a TemplateField section. You’ll need one TemplateField section for each field in the database that needs to look differently or be displayed differently than the default. The base TemplateField will look like this:

<asp:TemplateField>
</asp:TemplateField>

What you will probably want to address here, at a bare minimum is the ‘HeaderText‘ property. All your display properties for that field. If you want a different font, font color, etc – here’s where you’d put it.

Now, in between the open and close tags for the TemplateField, is where the magic happens. Generally, what is needed, is a different control, or specifically-sized textboxes, to keep the width of the GridView from spreading out as wide as it does, by default. So, the first thing we’d need would be an ItemTemplate. That’s the ‘default’ area. It the section that shows up when the GridView first appears. Here, you could create or add any control you want, however, for our purposes, since it’s just going to display the text, we’re going to add a label control to the ItemTemplate.

<ItemTemplate>
	<asp:Label ID="label1" Runat="server" />
</ItemTemplate>

Now – at this point, nothing is actually shown. As you’ll notice, there’s nothing assigned to the ‘Text‘ property of the label. Since we’re retrieving data from a database (in this scenario), we’ll assign the data from that particular field:
Continues…

Buttons and LinkButtons in ASP.NET

The reason this tutorial is called ‘Buttons and LinkButtons’ is because there is no real reason to have separate tutorials on them, since the properties, methods and general syntax is the same. They have the same general functionality, and the only difference is that the button, itself, looks like a regular button on the page, but a LinkButton looks like a text link. It is not, however, in any way, related to a hyperlink, which, at first glance, is what it resembles.

If you think you knew how to work with buttons before – think again.

The basic use of the button, entails an event handler (or subroutine) to do some action needed, when the button is clicked. So, the button control’s html would look like this:

<asp:Button id="btn1" Text="Click Me" onclick="btn1_Click" runat="server" />

Then, from this, youc an see that, to perform some action, it looks to the ‘btn1_Click‘ event handler (the subroutine that handles, or takes care of processing the action:

Sub btn1_Click(sender As Object, e As EventArgs)
          ' Do whatever you need here
End Sub

This still works just like it did, with earlier versions of ASP.Net. However, with the advent of 2.0, buttons now have much more power built in. Before, you could incorporate multiple buttons with similar functionality, using only 1 subroutine for all of them, but it was very limited. Let’s say there are two buttons, which share the same subroutine, called ‘btn1′ and ‘btn2′. The way you could handle this (you still can do it this way) would be something like this:
Continues…

Two Page Data Retrieval in ASP.NET

Here’s the scenario, using ASP.Net 2.0 (and above):
We have two web pages called GV1.aspx and NewPage.aspx. In GV1.aspx, we have a GridView, listing only a few fields from a database. From that page, we will designate one field as a HyperLinkField, so that, by clicking on it, we will be transferred to the second page (Newpage.aspx), using a QueryString. In that second page, we will retrieve all fields in the table based on the ID used in the QueryString.

This actually very easy to accomplish using ASP.Net 2.0, and most of the technology has already been included here, atASPNet101.comCode Sample – Master Detail Solution
Really, the only 2 new things are the use of the HyperLinkField and the two-page scenario.

For those of you who are familiar with ASP.Net 1.x, the HyperLinkField looks pretty much like the HyperLinkColumn, used with a DataGrid. The format is:

<asp:HyperLinkField DataTextField="au_lname"
	DataNavigateUrlFields="au_ID"
	DataNavigateUrlFormatString="NewPage.aspx?id={0}"
	HeaderText="Click For Details" />

Like the BoundField (or BoundColumn, with the DataGrid), it is not necessary to use a TemplateColumn.

In our scenario, the first page will consist of a GridView and SQLDataSource control only, using the Pubs database for the example. The last name field will be used for the Hyperlink:

<asp:GridView Runat="server" Id="gvAuthors" GridLines="Both" DataSourceID="SQLDS2" DataKeyNames="au_id" SelectedItemStyle-Backcolor="Pink" AllowPaging="True" AutoGenerateColumns="False"> <Columns> <asp:BoundField DataField="au_fname" HeaderText="au_fname" /> <asp:HyperLinkField DataTextField="au_lname" DataNavigateUrlFields="au_ID" DataNavigateUrlFormatString="NewPage.aspx?id={0}" HeaderText="Click For Details" /> <asp:BoundField DataField="state" HeaderText="state" /> </Columns> </asp:GridView>

The SQLDataSource control looks like this:

<asp:SqlDataSource ID="SQLDS2" runat="server"
	SelectCommand="SELECT [au_id], [au_lname], [au_fname], [state] FROM [Authors] Order by [state]"
ConnectionString="<%$ ConnectionStrings:Pubs %>">
</asp:SqlDataSource>

The ConnectionString here, is using the ConnectionString section of the Web.Config file, with an entry titled ‘Pubs’.

What happens on this page, is that, all the records are returned from the Authors table and, with the use of the HyperLinkField, the end-user is then, taken to the second page, based on the item selected in the GridView.

Now, on the second page (NewPage.aspx), we again have only two controls – a DetailsView and a SQLDataSource control. The DetailsView is fairly straightforward, using all BoundFields for display. Naturally, if there were other needs or possibilities here, we could use TemplateColumns, or add an Edit Button, etc:
Continues…

Using the QueryStringParameter in ASP.NET

If you have already read the ASPNet101.com tutorial on DataSource controls, you have seen the ControlParameter used. Here, we will look into another very handy class – the QueryStringParameter class.

Most likely, one of the first things you learned in either Classic ASP, or ASP.Net was how to send form results in your web pages. As you might recall, you probably learned about the Request Object, using Request.Form (with a POST, in Classic ASP), or Request.QueryString. When using a QueryString, to be able to capture the information in your page, you ‘added on’ to the actual url, with a question mark, followed by a key/value scenario:

MyPage.asp?name=Stewart

Then, on the ‘receiving’ page, whether it was the same or a separate page, you would then capture the data in the key/value and parse it somehow – something like: Dim strName as String (or without the ‘as’ clause, in Classic ASP)

strName=Request.QueryString("name")

Then, in that page, you could use the variable ‘strName’ wherever and however you liked. The most common use was/is to query a database, based on that variable. So, to use the variable in a SQL Select statement:

"Select * from [TableName] Where LName='" & strName & "'"

Of course, the code to connect and use that SQL Select Statement would then follow in the web page. Naturally, this is a very simplistic approach, but it’s most likely at least globally understandable at this point. This concept was easily do-able in Classic ASP and ASP.Net 1.x

Now – along comes v2.0 of ASP.Net. We find out that one of the key goals of the ASP.Net team was to reduce coding by as much as 70%. So, in doing so, new controls were created, like the different DataSource controls (SQLDataSource, AccessDataSource, etc). By having these controls do all the connecting and querying of the database, you might be wondering how to take care of a querystring scenario such as this. Don’t worry – it’s well handled.

Not only does the solution v2.0 has built in take care of it, but it handles the situation with Parameters, which is much safer than the concatenation shown above, in the SQL statement. Now, in your DataSource control, your SQL statement would look something like this:
Continues…