When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles [1.x] [2.0]
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips
Search

Sections:
Book Reviews
Sample Chapters
Commonly Asked Message Board Questions
Headlines from ASPWire.com
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
Web Hosts
XML Info
Information:
Advertise
Feedback
Author an Article
Technology Jobs

















internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers
ASP ASP.NET ASP FAQs Message Board Feedback ASP Jobs
Print this page.

Windows Systems Administrator
Jupitermedia
US-CT-Darien

Justtechjobs.com Post A Job | Post A Resume

Published: Friday, July 27, 2001

Creating a DataBound List of Radio Buttons
By Scott Mitchell


For More Information on ASP.NET
This article examines how to create a databound listbox using ASP.NET. For more information on ASP.NET be sure to check out the articles in the ASP.NET Article Index. The code in this article is based on the Beta 2 version of ASP.NET. To learn more about the free ASP.NET Beta 2, be sure to check out this FAQ.

- continued -

Introduction
A common task Web developers face is creating a form element (such as a series of checkboxes, radio buttons, or a listbox) whose members are populated by the contents of a database table. This is quite possible (and quite easy) to accomplish with ASP.NET In fact, in a previous article (Creating Databound DropDown Lists in ASP.NET), we examined how to create a databound listbox. In this article, we'll examine how to create a series of radio buttons whose values are automagically populated from a database table! We'll also look at how to respond to the user selecting a particular option and showing more detailed information based upon the radio button selected.

The Impetus
On 4Guys there is a Sample On-Line Chapters page, which lists a number of books that have free, on-line sample chapters. All of this information is stored in a database that contains two tables: tblPublishers and tblBooks. The tblPublishers contains a row for each publisher that has a book that appears in the sample chapters listing, while the tblBooks table contains a row for each sample book. Note that the tblBooks table contains a PublisherID column which serves as a foreign key to the tblPublishers table, tying a particular publisher to a particular book.

Wouldn't it be nice to generate a list of radio buttons based upon the publishers in the tblPublishers table? From this list, the user could select a particular publisher, at which point, the user would be shown a listing of books published by that particular publisher. In creating the radio button list, we could hard code the list of publishers, but that would be subject to change any time we added or removed publishers from the tblPublishers table. Ideally, the radio button list would be dynamically generated based upon the values in the tblPublishers table.

If you'd like to see what the end result will look like, check out the live demo. Pretty nice looking, eh? Realize that the radio button list was created dynamically using databind (essentially three lines of code in total). And this entire page, from start to finish, took me about four minutes to write. (I type fast. :-))

Creating the Databound Radio Button List
Creating a databound series of radio buttons is painfully simply with ASP.NET. We only really need to do three things:

  1. Create the asp:radiobuttonlist Web control, specifying the database columns we want to bind to the radio buttons' displayed text values and the hidden values that are passed along when the form is submitted.
  2. Write the code to populate a DataReader (or DataSet) with the applicable database information.
  3. Databind the DataReader (or DataSet) to the asp:radiobuttonlist Web control

That's it! So, let's examine each of these three steps. First, create the needed Web control in the HTML section of your ASP.NET Web page.

<html>
<body>
  <form runat="server">
    <b>Choose a Publisher's Books to View</b><br>
    <asp:radiobuttonlist id="radlstPubs" runat="server"
             DataValueField="PublisherID" DataTextField="Name" />
  </form>
</body>
</html>

The two most important things to notice is that we set the asp:radiobuttonlist Web control's DataValueField and DataTextField properties. Both properties should map to a column name in the database table that we wish to bind the radio button list to. The DataTextField property are the names that will be visually displayed next to each radio button; the DataValueField are the hidden values that are associated with each radio button. Also note that the radio button list was placed within a WebForm (the form tag with a runat="server" attribute).

Now that we've tackled our first step, let's look at performing our remaining two steps: reading the database table tblPublishers into a DataReader and binding the populated DataReader to the radio button list!

<% @Import Namespace="System.Data" %>
<% @Import Namespace="System.Data.SqlClient" %>
<script language="vb" runat="server">
  Sub Page_Load(sender as Object, e as EventArgs)
    If Not Page.IsPostBack then
      '*** STEP 1: Populate a DataReader ***
      'Create a connection
      Dim myConnection as New _
          SqlConnection(ConfigurationSettings.AppSettings("connectionString"))

      'Create the command object, passing in the SQL string
      Const strSQL as String = "SELECT PublisherID, Name FROM tblPublishers"
      Dim myCommand as New SqlCommand(strSQL, myConnection)

      'Open the connection and set the DataSource to the 
      myConnection.Open()
      
      'Populate the datareader
      Dim myDataReader as SqlDataReader
      myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)

      '*** STEP 2: Bind the DataReader to radlstPubs ***
      radlstPubs.DataSource = myDataReader
      radlstPubs.DataBind()  
    End If  
  End Sub

  ...
</script>

In the above Page_Load event handler we accomplish our two steps: populating a DataReader (in this case a SqlDataReader) with the contents of the tblPublishers table; and binding the resulting DataReader to our radio button list, radlstPubs. Note that we only wish to run this binding code on the first visit to the page (more on why later), hence we only perform the databinding if Page.IsPostBack is False, meaning that the page has not yet been posted back.

Now that we've looked at how to create a databound radio button list, let's turn our attention to responding to the user's selection of a particular radio button. In Part 2 we'll examine this aspect and the remainder of our application!

  • Read Part 2!


    Windows Internet Technology | ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article



  • JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
    Microsoft Article: 7.0, Microsoft's Lucky Version?
    Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Windows Server 2008
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES