Creating a 'States' User Control in ASP.NET

A good example of a particular repeatable scenario within a website would be a DropDownList of States (for those living in the United States, of course). There’s no need to create the code for this scenario multiple times within a web site. The best choice is to create a User Control for this, if you have multiple places where it can be used.

Let’s start off by creating the DropDownList on the page:

<asp:DropDownList id="ddlStates" runat="server"/>

Now, let’s populate the DropDownList with the states (some of you will recognize this from a previous Code Sample).

Sub Page_Load(Source as Object, E as EventArgs) if not Page.IsPostBack then Dim sStates() as string={"","AK", "AL", "AR", "AS", "AZ", "CA", "CO", "CT", _ "DC", "DE", "FL", "GA", "GU", "HI", "IA", "ID", "IL", "IN", "KS", "KY", "LA", _ "MA", "ME", "MD", "MI", "MN", "MO", "MP", "MS", "MT", "NC", "ND", "NE", _ "NH", "NJ", "NM", "NV", "NY", "OH", "OK", "OR", "PA", "PR", "RI", "SC", "SD", _ "TN", "TX", "UT", "VA", "VI", "VT", "WA", "WI", "WV", "WY"} ddlStates.datasource=sStates ddlStates.databind() end if End Sub

So far, that’s pretty straightforward, but since we won’t be accessing the DropDownList directly, inside the User Control, we must create properties which can be used to do what we need, for any properties which aren’t intrinsically inherited. For this example, we’ll create a SelState Property and a TabIndex Property. You’ll most likely recognize the TabIndex property from other controls. Here, since you’re creating your own properties, you can call it anything you’d like. For the sake of simplicity, we’re calling it ‘TabIndex’ so that it’s function will be automatically recognized. To do this, here’s the code:
Continues…

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>