asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search





Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














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

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Creating a Web Custom Control -- Cont'd
By Conrad Jalali


  • email this article to a colleague
  • suggest an article

    Table of Contents

    • Page 1
      • Prerequisites
      • Introduction
      • Some Background on Controls
      • Planning for Project Reuse
      • Data-Bound Properties
      • CSS and Other Visual Properties

    • Page 2
      • The Render Method
      • The HTML Output by the Control
      • Design-Time Support

    • Page 3
      • Using the Control
      • Conclusion
      • About the Author

    Using the Control

    The easiest way to use a custom control is by dragging and dropping it from the Toolbox onto a page. To add our control to the Toolbox, right-click on the Toolbox and select "Add/Remove Items":

    This will bring up a dialog box. Browse for .NET Framework Components on your PC and specify the DLL for your Web Control Library project. Remember that the DLL location will be bin\Debug folder under your project folder if you built the project in the Debug configuration, and in bin\Release if you compiled under the Release configuration.

    Once you have selected the DLL, you should see a component named CategorizedCheckBoxList, which can be selected:

    After clicking "OK", the CategorizedCheckBoxList should now appear in your Toolbox:

    To use the CategorizedCheckBoxList on an ASPX page, drag and drop the control from the Toolbox onto the page (in Design view in VS .NET). Once the control is on your page, you can set the number of columns used in the display, and the CSS properties.

    The DataTable should be specified in your code behind file, to ensure the table has been populated before the CategorizedCheckBoxList tries to access it. You can specify the names for the category, text, and value columns either in the code-behind file or in the ASPX page.

    Let's take a look at the Default.aspx page included in the sample project that accompanies this article. Here is the Page_Load method:

    private void Page_Load(object sender, System.EventArgs e)

    {

         // If the page has not posted-back, or if it has but the "Show List" checkbox is checked,

         // get the data for our CategorizedCheckBoxList.

         if(!IsPostBack || chkShowList.Checked == true)

         {

               // Get the data

               GetMdbData();

         }

         else

         {

               // Hide the CategorizedCheckBoxList

               CategorizedCheckBoxList1.Visible = false;

     

               // Hide the "Show List" checkbox

               chkShowList.Visible = false;

     

               // Hide the submit button, too

               btnTestValues.Visible = false;

         }

    }

    We're only retrieving the data for the control if the control is going to be displayed. (If we were using dynamically-instantiated CheckBoxList controls, we would need to get the data every time, regardless of the visibility of the controls.)

    Next, we call the method, GetMdbData, which selects the data from an Access database:

    protected void GetMdbData()

    {

         // Create a connetion

         OleDbConnection Conn = new OleDbConnection();

         Conn.ConnectionString = String.Concat("Provider=Microsoft.Jet.OleDb.4.0;data source=", Server.MapPath("SampleData.mdb"));

     

         // Build a data adapter that selects all of the columns and rows

         // in a saved query called qryCarModelCarMaker, in the Access database

         OleDbDataAdapter Adp = new OleDbDataAdapter("SELECT * FROM qryCarModelCarMaker", Conn);

        

         // Create an instance of our Cars typed dataset

         Cars TypedSampleData = new Cars();

     

         // Use the adapter to fill the CarTable

         Adp.Fill(TypedSampleData, "CarTable");

     

         // Specify the data properties for our CategorizedCheckBoxList control

         CategorizedCheckBoxList1.DataTable = TypedSampleData.CarTable;

         CategorizedCheckBoxList1.DataTextColumn = "Model";

         CategorizedCheckBoxList1.DataValueColumn = "CarModelPK";

         CategorizedCheckBoxList1.DataCategoryColumn = "Make";

     

         // Clean-up

         Conn.Dispose();

         Adp.Dispose();

    }

    Although we're using a typed DataSet, which is filled by a dynamic database query, the CategorizedCheckBoxList only cares about the DataTable, and the names of the columns that contain the required data. Other pages in the example project load both typed and un-typed data from XML files.

    view screenshot

    After making a few selections, clicking on the "Test Checkbox Values" button will display the values of the selected checkboxes. In our example, these are the primary key values for the car models that were picked. Let's see how to retrieve the selected values:

    private void btnTestValues_Click(object sender, System.EventArgs e)

    {

         // Were any checkboxes checked?

         if(CategorizedCheckBoxList1.Selections.Count > 0)

         {

               // Yes. Let's use a string builder to tell the user what we find.

               StringBuilder Sb = new StringBuilder();

               Sb.Append("The following values were selected:");

              

               // Use an HTML un-ordered list to display the values

               Sb.Append("<ul>");

        

               // Loop through the selections

               foreach(string check in CategorizedCheckBoxList1.Selections)

               {

                    // Add this item to our HTML list

                    Sb.Append("<li>");

                    Sb.Append(check);

                    Sb.Append("</li>");

               }

     

               // End the list

               Sb.Append("</ul>");

     

               // Set the text of our label

               Label1.Text = Sb.ToString();

         }

         else

         {

               // Use our label to tell the user that nothing was picked.

               Label1.Text = "No checkboxes were selected.";

         }

    }

    When the method executes, the values of the selected checkboxes are listed:

    I'm almost finished covering the nuts and bolts of the CategorizedCheckBoxList, but we still haven't talked about how to specify default selections. Our control makes it easy to specify pre-selected options, by simply referencing the public property, Selections, which is an ArrayList:

    // If the page has not posted-back, or if it has but the "Show List" checkbox is checked,

    // get the data for our CategorizedCheckBoxList.

    if(!IsPostBack || chkShowList.Checked == true)

    {

         // Get the data

         GetMdbData();

     

         // Select all of the Audi models

         CategorizedCheckBoxList1.Selections.Add("37");

         CategorizedCheckBoxList1.Selections.Add("38");

         CategorizedCheckBoxList1.Selections.Add("39");

         CategorizedCheckBoxList1.Selections.Add("40");

         CategorizedCheckBoxList1.Selections.Add("41");

    }

    Just remember that you need to put string values into the ArrayList, and you'll be all set.

    Conclusion

    The .NET Framework includes a rich toolbox of Web controls, and you should always try to use a standard control before committing to the development of a custom control. The standard Web controls are quite a bit more complex than my example. They offer support for up-level and down-level web browsers, and provide a rich event model. And you can count on Microsoft to upgrade their web controls with each new release of ASP.NET.

    But when you can't find a control that meets your need, don't be afraid to write your own. Although complicated in comparison to user controls, Web custom controls are not too difficult to tackle, and they provide a host of benefits. The great equalizer is HTML, which is used to render all controls. If you can figure out how to represent your idea in HTML, you can build a Web custom control.

    About the Author

    Conrad Jalali is the co-founder of Useful Studios, a design firm focused on usability. He has been working with Active Server Pages for the past five years, and specializes in ASP.NET with C# and SQL Server 2000. Conrad graduated from Sarah Lawrence College with a Bachelor of Arts in Liberal Arts, and is a Microsoft Certified Professional. He lives in the Washington, DC area, with his wife, Elizabeth, and his dog, Sparky. He can be reached via email at conrad@smallcog.com.

    << The Render Method

    Rate This Article

  • Other Articles
    Apr 21, 2004 - Creating a Web Custom Control
    Conrad Jalali shows how to build Web custom controls by creating one that displays checkboxes in a categorized, hierarchical view.
    [Read This Article]  [Top]
    Mar 15, 2004 - Creating a Popup Date Picker
    Conrad Jalali shows how to extend the functionality of the ASP.NET Calendar control to remove some of the annoying postback delays that occur when populating a text box with a date from a popup calendar.
    [Read This Article]  [Top]
    Oct 23, 2003 - Creating a Custom .NET Web Control With Events
    This article covers some of the essentials of building reusable Web controls. Learn how to create a Web control and its custom events and event arguments, as well as how to use the control properly within a page.
    [Read This Article]  [Top]
    Aug 12, 2003 - Creating a Generic Pager Control
    ASP.NET provides only one control that supports paging, the DataGrid. Tomasz Kaszuba shows how to build and implement a custom pager for different controls that change depending on the data source or presentation.
    [Read This Article]  [Top]
    Jun 10, 2003 - Hosting .NET Windows Forms Controls in IE
    Windows Forms within Web pages work in a manner similar to Java applets. Thiru Thangarathinam shows how to host Windows Forms controls in Internet Explorer and how to utilize .NET Code Access Security to configure what the control can do when running within the browser.
    [Read This Article]  [Top]
    May 6, 2003 - Building a Simple Mask Control
    James Culshaw shares his experiences building his first working custom control, a basic mask control that allows input of time values, and offers advice and tips to those just starting out.
    [Read This Article]  [Top]
    Mar 3, 2003 - Creating a Server Control for JavaScript Testing
    Learn how to create an ASP.NET server control that detects if a browser supports JavaScript AND if JavaScript is enabled.
    [Read This Article]  [Top]
    Jan 21, 2003 - Protecting Users from Suspect Textual Data
    Learn the ins and outs of composite controls by creating an application that prevents users from submitting offending text.
    [Read This Article]  [Top]
    Nov 26, 2002 - Introduction to the .NET Speech SDK
    Rob Chartier offers a tour of the .NET Speech SDK Beta 2 and its use of the industry specification SALT. The article shows you how to create a basic speech-enabled Web user control.
    [Read This Article]  [Top]
    Aug 27, 2002 - Creating "Self Populating" Controls
    In this article, Luther Stanton shows how to combine inheritance and server controls to create a self-populating drop-down-list control.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry



    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