Thursday, March 3, 2011

Databound DropDownLists

So you want to populate a DropDownList with values from a database, huh? Well, it is not incredibly hard. You can do it from the designer by hovering over the DropDownList and selecting "Choose Data Source..." from the smart tag. You can also do it from code like so:


  1.         <asp:DropDownList ID="DropDownList1" runat="server"
  2.            DataSourceID="SqlDataSource12" DataTextField="linkShortDesc"
  3.            DataValueField="linkShortDesc">
  4.         </asp:DropDownList>
  5.         <asp:SqlDataSource ID="SqlDataSource12" runat="server"
  6.            ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
  7.             SelectCommand="SELECT [linkShortDesc] FROM [Links]"></asp:SqlDataSource>

As you can see from the code, we created a new ASP.NET SqlDataSource, provided our connection string and our query we wanted to run. In my case I'm returning a list of links from a table. Now, in our ASP.NET DropDownList code, we can specify a DataValueField and a DataSourceID. The DataSourceID is the ID of the data source we want to link to, and DataValueField is the name of the column we want to display in our drop down list.

Happy coding!

ASP.NET Menu Control

Navigation is nice. And so is implementing navigation easily. It is really cool that ASP.NET and Visual Studio will help us with this, with the Menu control.

In your toolbox, go to the "Navigation" tab and double click "Menu" on the list. This will add a new menu control to your page. The Menu control is easier to use in design mode, so switch to design mode.

If you hover over your menu control, the smart tag should appear (the little arrow usually to the right). It gives us some options (I won't list all of them here):

  • Auto format: This will open a dialog to quickly apply themes to your menu control. Go ahead, select one.
  • Views: (Static or Dynamic): Static view is where the links for your menu are always visible on the screen. Useful if you want something similar to a navigation bar at the top of the screen. Dynamic: allows for some fancy animations and other useful features. Useful if you want to preserve screen real-estate.
  • Edit Menu Items: This will open a dialog where you can add items to your menu. Root items will appear on the menu bar and children items will appear below their corresponding root items.
How to change the orientation of the menu control:

After you select your menu control, go to the properties page of Visual Studio and find "Orientation". It has two possibilities: Horizontal or Vertical. Just like you would think, Horizontal gives the menu control a horizontal orientation and vertical gives the menu control a vertical orientation.

To do this in code:

However, this can be accomplished through the code window. I will show you the code, and then explain it.

  1.  <asp:Menu ID="Menu1" runat="server" Orientation="Horizontal">
  2.         <Items>
  3.             <asp:MenuItem Text="Home" Value="Home"></asp:MenuItem>
  4.             <asp:MenuItem Text="About Us" Value="About Us"></asp:MenuItem>
  5.             <asp:MenuItem Text="Contact Us" Value="Contact Us"></asp:MenuItem>
  6.             <asp:MenuItem Text="Services" Value="Services">
  7.                 <asp:MenuItem Text="I Break Code Blog" Value="I Break Code Blog"></asp:MenuItem>
  8.                 <asp:MenuItem Text="Open Source Software" Value="Open Source Software">
  9.                 </asp:MenuItem>
  10.             </asp:MenuItem>
  11.         </Items>
  12.  </asp:Menu>

Lines 1 and 13 define the region of code which will contain the ASP.NET Menu Control. The Menu Control is contained between the <asp:Menu> tag and the </asp:Menu> tag. If you notice, the <asp:Menu> tag has a few attributes associated with it in this example:

  • runat: Determines where an element is processed. 'Server' controls are processed before the website is sent to the browser.
  • Orientation: gets or sets the direction in which to render the Menu control.
Lines 2 and 11 define the region of code where the ASP.NET Menu Control items are defined. The Menu Control items are contained between the <Items> tag and the </Items> tag.

The individual ASP.NET Menu Control items are defined with the <asp:MenuItem> and </asp:MenuItem> tags.

If you look at this code: <asp:MenuItem Text="About Us" Value="About Us"></asp:MenuItem>
you will see the attributes 'Text' and 'Value':
  • The 'Text' attribute sets the text displayed in the ASP.NET Menu Control
  • The 'Value' attribute sets the text associated with the Menu Control that will not be displayed on the ASP.NET Menu Control
External Resources Related To: ASP.NET Menu Control

Master Pages, Content Pages and Content Place Holders

Master Pages save a web developer a lot of design hassle when building web applications (or websites). Essentially, they are a template for pages within your web application.

To create a master page in Visual Studio, click the 'Website' menu button and then click 'Add New Item...'. When the Add New Item dialog appears, choose 'Master Page' from the list and then give it a name. Then click 'Add'.

Visual Studio will create a file that looks like this:

  1. <%@ Master Language="VB" CodeFile="myMasterPage.master.vb" Inherits="myMasterPage" %>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5.     <title></title>
  6.     <asp:ContentPlaceHolder id="head" runat="server">
  7.     </asp:ContentPlaceHolder>
  8. </head>
  9. <body>
  10.     <form id="form1" runat="server">
  11.     <div>
  12.         <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
  13.        
  14.         </asp:ContentPlaceHolder>
  15.     </div>
  16.     </form>
  17. </body>
  18. </

If you look at the code, you will see content placeholder controls. These are used by content pages, which are derived from your master pages. Master pages are the page template, and content pages contain the content of your web page.

Content place holders define areas in your master page where the content is replaceable inside your content pages.

To create a content page, go to the Solution Explorer within Visual Studio, and right click on your master page and choose "Add Content Page". This will create a new content page that is linked to the master page you selected. This means that all the content placeholders you created in your master page will appear in your content page.

Note: When dealing with content pages, you can only put content in a content placeholder.

The new content page should look similar to this:

  1. <%@ Page Title="" Language="VB" MasterPageFile="~/myMasterPage.master" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
  2. <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    Header content goes here
  3. </asp:Content>
  4. <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    Our content goes here.
  5. </asp:Content>

Friday, February 11, 2011

Form Validation

ASP.NET makes it really simple, maybe to simple, to add form validation to your web forms. Suppose we had a simple form that consisted of these fields:


  • First Name
  • Last Name
  • Email Address
The code for such a form would probably resemble this:

  1.  <form id="simpleForm" runat="server">
  2.     <div>
  3.    
  4.         First Name:<asp:TextBox ID="txtFName" runat="server"></asp:TextBox>
  5.         <br />
  6.         Last Name:<asp:TextBox ID="txtLName" runat="server"></asp:TextBox>
  7.         <br />
  8.         Email Address:<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
  9.         <br />
  10.        
  11.     </div>
  12.  </form>

After we add our validation controls, which you can add from the "Validation" tab of the Toolbox, the code looks like this:

  1.     <form id="signUp" runat="server">
  2.     <div style="width: 957px">
  3.    
  4.         First Name:<asp:TextBox ID="txtFName" runat="server"></asp:TextBox>
  5.         <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
  6.             ControlToValidate="txtFName" ErrorMessage="First Name Required"></asp:RequiredFieldValidator>
  7.         <br />
  8.         Last Name:<asp:TextBox ID="txtLName" runat="server"></asp:TextBox>
  9.         <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
  10.             ControlToValidate="txtLName" ErrorMessage="Last Name Required"></asp:RequiredFieldValidator>
  11.         <br />
  12.         Email Address:<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
  13.         <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
  14.             ControlToValidate="txtEmail" ErrorMessage="Enter a vaild email address"
  15.             ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
  16.         <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
  17.             ControlToValidate="txtEmail" ErrorMessage="Email address required"></asp:RequiredFieldValidator>
  18.         <br />
  19.        
  20.     </div>
  21.     </form>

And what will happen now is our web form will make the First Name, Last Name and email fields required, as well as validate that the email address is really an email address.

Yield: Button redirection

Sometimes it is necessary to provide a way to get from one web page to another. Normally this is done with links, but sometimes you might come across a situation where you need to do this from within your code.

This can be accomplished in ASP.NET by using the "Response" property of the current web form. Keep in mind that the "Response" property is just a System.Web.HttpResponse(), and this means that anything we could do with the System.Web.HttpResponse(), we can do with the "Response" property of our web form.

Linking to an external web page using the "Response" property of the web form:
  1. Response.Redirect("http://ibreakcode.blogspot.com")

Linking to an internal web page using the "Response" property of the web form:
  1. Response.Redirect("Default2.aspx")

And thats about all there is to that.

Creating A Blank ASP.NET Project

Microsoft Visual Studio 2010 gives you a few options to create an ASP.NET website pre-loaded with a bunch of websites already built for you. This is great if you just want something to play around with something, but don't do you much good if you don't know whats going on.

For this reason, the remainder of the ASP.NET posts, unless otherwise noted will be using blank ASP.NET website projects.

To create a blank ASP.NET website project, open Microsoft Visual Studio and follow these steps:



  1. Click the "File" menu option on the main menu
  2. Click the "New" sub-menu option
  3. Click the "Web Site..."
After you click the menu option in Step 3 , the following dialog will appear (Note: I'm using Microsoft Visual Studio 2010 Professional):


On the dialog box, you will see something titled "Web location" and you should have the following options:
The "New Web Site" dialog.

  • File System
    • This creates a website on your local file system. Such as C:\Websites. These website are not available to the actual Internet via IIS or other server technologies, unless you create a virtual directory pointing to them. 
  • HTTP
    • These are IIS websites located on the local computer, or a remote computer.
  • FTP
    • These are websites that you connect to with FTP. You will need to provide credentials to access the FTP server.
More information on ASP.NET web locations can be found here.
    When selecting the project template, choose "ASP.NET Empty Web Site". This will create a blank ASP.NET project where you can add your own web site components.

    Microsoft has an example project that you can play around with if you choose "ASP.NET Web Site"

    Monday, January 24, 2011

    The Frog Database

    The AmphibiaWeb website shows the different amphibians in different regions of the world. The link will show you the amphibians in the United States, organized by U.S. states.

    We are going to create a simple database that uses some of the data from this website. This post will use the data from Wyoming, located here.

    The website contains the following columns from their database:
    • Scientific Name
    • Photo
    • Map
    • Sound
    • IUCN Red List Status
    • Vernacular Name
    • Family
    Our database table will only utilize four of the columns:
    • Scientific Name
    • IUCN Red List Status
    • Vernacular Name
    • Family
    Here will be our database structure:

    Database: Amphibians
    Table(s): Wyoming

    First, lets create the database and table. We will only insert a few of the records:

    1. CREATE DATABASE Amphibians;
    2. GO
    3. USE Amphibians;
    4. GO
    5. CREATE TABLE Wyoming
    6. (
    7.     amph_ID INT IDENTITY(1,1) PRIMARY KEY
    8.     , scientific_Name VARCHAR(100)
    9.     , rl_Status VARCHAR(75)
    10.     , vernacular_Name VARCHAR(100)
    11.     , family VARCHAR(100)
    12. );
    13. INSERT INTO Wyoming
    14. (
    15.     scientific_Name
    16.     , rl_Status
    17.     , vernacular_Name
    18.     , family
    19. )
    20. VALUES
    21. (
    22.     'Bufo baxteri'
    23.     , 'Extinct in the Wild (EW)'
    24.     , 'Wyoming Toad'
    25.     , 'Bufonidae'
    26. );
    27. INSERT INTO Wyoming
    28. (
    29.     scientific_Name
    30.     , rl_Status
    31.     , vernacular_Name
    32.     , family
    33. )
    34. VALUES
    35. (
    36.     'Bufo boreas'
    37.     , 'Near Threatened (NT)'
    38.     , 'Western Toad'
    39.     , 'Bufonidae'
    40. );
    41. INSERT INTO Wyoming
    42. (
    43.     scientific_Name
    44.     , rl_Status
    45.     , vernacular_Name
    46.     , family
    47. )
    48. VALUES
    49. (
    50.     'Bufo cognatus'
    51.     , 'Least Concern (LC)'
    52.     , 'Great Plains Toad'
    53.     , 'Bufonidae'
    54. );
    55. INSERT INTO Wyoming
    56. (
    57.     scientific_Name
    58.     , rl_Status
    59.     , vernacular_Name
    60.     , family
    61. )
    62. VALUES
    63. (
    64.     'Bufo hemiophrys'
    65.     , 'Least Concern (LC)'
    66.     , 'Canadian Toad'
    67.     , 'Bufonidae'
    68. );

    If you run a select all query on the new Amphibians table, you should get this result:

    ---------------------------------------------------------------------------------------

    amph_ID scientific_Name rl_Status vernacular_Name family
    1 Bufo baxteri Extinct in the Wild (EW) Wyoming Toad Bufonidae
    2 Bufo boreas Near Threatened (NT) Western Toad Bufonidae
    3 Bufo cognatus Least Concern (LC) Great Plains Toad Bufonidae
    4 Bufo hemiophrys Least Concern (LC) Canadian Toad Bufonidae


    I Break Code Where code gets done.
    ASP.NET | HTML | SQL Server | VB.NET | Request A Topic |