DropDownList ASP.NET Server Control

DropDownList ASP.NET Server Control"-->

only for RuBoard

DropDownList ASP.NET Server Control

The DropDownList control enables item selection from a drop-down ListBox . For example, if your site requires a user to enter their year of birth you can have a DropDownList populated with years ranging from 1900 to present from which the user can select.

Another example would be if your site wanted users to enter their address and, instead of the full state name , only the states' abbreviations ”(Washington “WA). You can force them to enter it correctly by making them choose it from the DropDownList .

The DropDownList is the first of the list controls that we will go over. Even though each of the list controls are different in their functionality they are made up of the same guts ”the ListItem . The ListItem represents one item in the list control. When you want to add an item to the list control you add a ListItem object. There are three ways to add a ListItem to the DropDownList ”Listing 8.10 demonstrates all of them. The DropDownList can also be dynamically populated by setting its DropDownList.DataSource , which I'll discuss later in the chapter.

Listing 8.10 Adding Items to the DropDownList
 [VisualBasic.NET] 01: <script runat="server" language="vb" > 02: 03:  public sub Page_Load(sender as Object, e as EventArgs) 04: 05:   ddl.Items.Add(new ListItem("This is Method Three", 3.ToString())) 06: 07:  end sub 08: 09: </script> [C#.NET] 01: <script runat="server" language="C#" > 02: 03:  void Page_Load(Object sender, EventArgs e) { 04: 05:   ddl.Items.Add(new ListItem("This is Method Three", 3.ToString())); 06: 07:  } 08: 09: </script> [VisualBasic.NET & C#.NET] 10: <html> 11:  <body> 12:   <form runat="server"> 13: 14:    <asp:DropDownList runat="server" id="ddl" > 15:     <asp:ListItem Value="1" Text="This is Method One" /> 16:     <asp:ListItem Value="2">This is Method Two</asp:ListItem> 17:    </asp:DropDownList> 18: 19:   </form> 20:  </body> 21: </html> 

The DropDownList control can be found on lines 14 “17. The first method I use to add a ListItem can be found on line 15 where all values are contained within one ListItem element. The second method is on line 16 where the Value attribute is within the opening ListItem element and the text is between the opening and closing ListItem element. The third method is done dynamically through code (lines 3 “7) in the Page.Load event. I use the ListItemsCollection.Add method passing in a new ListItem object (line 5). You might be wondering where the ListItemsCollection object came from ”it was accessed through the DropDownList.Items property. The ListItemCollection is a zero-based collection of ListItem objects. Like nearly everything in .NET you can write code to add a new ListItem many different ways. I wrote it this way for the simple fact that it requires the least amount of code.

In Listing 8.10, I created a new ListItem by passing in the Text and Value of the ListItem directly into the object constructor. There are actually three overloads for the ListItem contructor. We will not being going into detail for each one, but the following list contains them:

  • ListItem myListItem = new ListItem();

  • ListItem myListItem = new ListItem( string-for-text);

  • ListItem myListItem = new ListItem( string-for-text, string-for-value);

If you were to view the source on the rendered page when using the single-line TextBox , you would see the following:

 01:    <select name="ddl" id="ddl"> 02:         <option value="1">This is Method One</option> 03:         <option value="2">This is Method Two</option> 04:         <option value="3">This is Method Three</option> 05:    </select> 

Look famililar? The DropDownList generates a SELECT HTML element. Figure 8.4 is an illustration of the page once rendered with the ListBox open showing all three items added.

Figure 8.4. All three ListItems have been added to the same DropDownList .
graphics/08fig04.gif

Raising and Handling Events and Determining Item Selection

I have often seen drop-down lists used for Web site navigation where a user will select an item from the list and the page will immediately navigate to the desired section of the site. This is nothing new and exciting, but is a bit different to implement when using the DropDownList .

The DropDownList.AutoPostBack property behaves similar to that of the TextBox.AutoPostBack in that when a user makes a change to the DropDownList the page is automatically posted back to the server. The difference is that the text isn't changing in the DropDownList as in the TextBox . Instead, when a user changes the DropDownList.SelectedItem the page is posted back to the server. The DropDownList.SelectedIndex is the index of the ListItem within the ListItemCollection that is selected ”as a reminder the ListItemCollection is zero based.

The DropDownList.OnSelectedIndexChanged attribute behaves similar to that of the TextBox.OnTextChanged attribute. When a user makes a change to the DropDownList and the page is posted back to the server an event is raised ”( DropDownList.SelectedIndexChanged ) ”and you can handle this event by setting the DropDownList.OnSelectedIndexChanged equal to the name of the method you want to handle it. The difference between the two the change that takes place ”a change to the DropDownList.SelectedIndex .

In Listing 8.11, I demonstrate how to use these two attributes. Additionally, I show how to retrieve and set the DropDownList.SelectedItem .

Listing 8.11 Raising and Handling Events and Determining Item Selection
 [VisualBasic.NET] 01: <script runat="server" language="vb" > 02: 03:  public sub Page_Load(sender as Object, e as EventArgs) 04: 05:   if (Not IsPostBack) then 06:    ddl_AddItems() 07:   end if 08: 09:  end sub 10: 11:  public sub ddl_AddItems() 12: 13:   dim i as integer 14:   for i = 0 to 4 15:    ddl.Items.Add(new ListItem("This is Index - " & i)) 16:   next 17: 18:  end sub 19: 20:  public sub ddl_SelectedIndexChanged(sender as Object, e as EventArgs) 21: 22:   dim sb as new StringBuilder() 23:   sb.Append("DropDownList.SelectedIndex = ") 24:   sb.Append(ddl.SelectedIndex) 25:   sb.Append("<br>") 26:   sb.Append("DropDownList.SelectedItem = ") 27:   sb.Append(ddl.SelectedItem.Text) 28: 29:   lblSelectedItem.Text = sb.ToString() 30: 31:  end sub 32: 33: </script> [C#.NET] 01: <script runat="server" language="C#" > 02: 03:  void Page_Load(Object sender, EventArgs e) { 04: 05:   if (! IsPostBack) { 06:    ddl_AddItems(); 07:   } 08: 09:  } 10: 11:  void ddl_AddItems(){ 12: 13:   int i; 14:   for (i = 0; i < 5; i++){ 15:    ddl.Items.Add(new ListItem("This is Index - " + i)); 16:   } 17: 18:  } 19: 20:  void ddl_SelectedIndexChanged(Object sender, EventArgs e){ 21: 22:   StringBuilder sb = new StringBuilder(); 23:   sb.Append("DropDownList.SelectedIndex = "); 24:   sb.Append(ddl.SelectedIndex); 25  sb.Append("<br>"); 26:   sb.Append("DropDownList.SelectedItem = "); 27:   sb.Append(ddl.SelectedItem.Text); 28: 29:   lblSelectedItem.Text = sb.ToString(); 30: 31:  } 32: 33: </script> [VisualBasic.NET & C#.NET] 34: <html> 35:  <body Style="font-Size:10"> 36:   <form runat="server"> 37:    <h3>DropDownList</h3> 38: 39:    <asp:Label id="lblSelectedItem" runat="server" /> 40: 41:    <p> 42: 43:    <asp:DropDownList 44:     runat="server" 45:     id="ddl" 46:     AutoPostBack="true" 47:     OnSelectedIndexChanged="ddl_SelectedIndexChanged" 48:     /> 49: 50:   </form> 51:  </body> 52: </html> 

Let's start with the DropDownList control (lines 43 “48) in Listing 8.11. On line 46 I have the AutoPostBack property set to true . This means that as soon as the DropDownList.SelectedIndex changes the page will post back to the server. On line 47 is OnSelectedIndexChanged and it is set to ddl_SelectedIndexChanged . This means that when the DropDownList.SelectedIndex changes and the page is posted back to the server, ddl_SelectedIndexChanged (lines 20 “31) will handle the SelectedIndexChaned event.

You might be wondering why the DropDownList is only populated on the first page request and not on a post back (lines 3-9). This is because the Page.Load event is fired before the DropDownList.SelectedIndexChanged event is. If you were to re-bind the DropDownList on every request, then the DropDownList would be refreshed to its original state and the DropDownList.SelectedIndex value would always be 0.

Within the ddl_SelectedIndexChanged I retrieve two values. The first is the DropDownList.SelectedIndex and the second is the DropDownList.SelectedItem.Text ”this is the selected items text that is displayed to the user ”"This is Index “2". The DropDownList.SelectedItem exposes a ListItem object for the item that selected. What this means is you have access to all the ListItem attributes ”for example, Text , Value , Selected . In this example I access the Text attribute.

Binding a DropDownList to a Data Source

One of the greatest things about all the list controls is that they can be bound to a data source with more than one record and the ListItemCollection automatically will be made. For example, you can populate a DropDownList from a DataTable and a ListItem automatically will be generated for each row in the DataTable .

If you want to bind the DropDownList to a data source then you must set the DropDownList.DataSource equal to the object you want to bind to ”this can be any data source that supports the ICollection interface ” DataTable , DataView , or ArrayList .

You can control which fields from the DropDownList.DataSource are used when the DropDownList 's ListItemCollection is created by using two properties:

  • DataTextField The name of the field you want to populate ListItem.Text (this is what's shown to the user)

  • DataValueField The name of the field you want to populate ListItem.Value (this is the value for the item)

Listing 8.12 demonstrates how to dynamically populate the DropDownList from a database.

Listing 8.12 Data Binding the DropDownList
 [VisualBasic.NET] 01: <%@ Import Namespace="System.Data" %> 02: <%@ Import Namespace="System.Data.SqlClient" %> 03: <script runat="server" language="vb" > 04: 05:  public sub Page_Load(sender as Object, e as EventArgs) 06: 07:   if (not IsPostBack) then 08:    ddl_DataBind() 09:   end if 10: 11:  end sub 12: 13:  public sub ddl_DataBind() 14: 15:   dim SqlCon as new SqlConnection("server=localhost; uid=sa;pwd=;database=northwind") 16:   dim SqlCmd as new SqlCommand("SELECT ProductName, ProductID FROM Products", SqlCon) 17: 18:   SqlCon.Open() 19:   ddl.DataSource = SqlCmd.ExecuteReader(CommandBehavior.CloseConnection) 20:   ddl.DataTextField = "ProductName" 21:   ddl.DataValueField = "ProductID" 22:   ddl.DataBind() 23: 24: 25:  end sub 26: 27:  public sub ddl_SelectedIndexChanged(sender as Object, e as EventArgs) 28: 29:   dim sb as new StringBuilder() 30:   sb.Append("DropDownList.SelectedItem Value = ") 31:   sb.Append(ddl.SelectedItem.Value) 32:   sb.Append("<br>") 33:   sb.Append("DropDownList.SelectedItem = ") 34:   sb.Append(ddl.SelectedItem.Text) 35: 36:   lblSelectedItem.Text = sb.ToString() 37: 38:  end sub 39: 40: </script> [C#.NET] 01: <%@ Import Namespace="System.Data" %> 02: <%@ Import Namespace="System.Data.SqlClient" %> 03: <script runat="server" language="C#" > 04: 05:  void Page_Load(Object sender, EventArgs e) { 06: 07:   if (! IsPostBack) { 08:    ddl_DataBind(); 09:   } 10: 11:  } 12: 13:  void ddl_DataBind(){ 14: 15:   SqlConnection SqlCon = new SqlConnection("server=localhost; graphics/ccc.gif uid=sa;pwd=;database=northwind"); 16:   SqlCommand SqlCmd = new SqlCommand("SELECT ProductName, ProductID FROM Products", graphics/ccc.gif SqlCon); 17: 18:   SqlCon.Open(); 19:   ddl.DataSource = SqlCmd.ExecuteReader(CommandBehavior.CloseConnection); 20:   ddl.DataTextField = "ProductName"; 21:   ddl.DataValueField = "ProductID"; 22:   ddl.DataBind(); 23: 24: 25:  } 26: 27:  void ddl_SelectedIndexChanged(Object sender, EventArgs e){ 28: 29:   StringBuilder sb = new StringBuilder(); 30:   sb.Append("DropDownList.SelectedItem Value = "); 31:   sb.Append(ddl.SelectedItem.Value); 32:   sb.Append("<br>"); 33:   sb.Append("DropDownList.SelectedItem = "); 34:   sb.Append(ddl.SelectedItem.Text); 35: 36:   lblSelectedItem.Text = sb.ToString(); 37: 38:  } 39: 40: </script> [VisualBasic.NET & C#.NET] 41: <html> 42:  <body Style="font-Size:10"> 43:   <form runat="server"> 44:    <h3>DropDownList</h3> 45: 46:    <asp:Label id="lblSelectedItem" runat="server" /> 47: 48:    <p> 49: 50:    <asp:DropDownList 51:     runat="server" 52:     id="ddl" 53:     AutoPostBack="true" 54:     OnSelectedIndexChanged="ddl_SelectedIndexChanged" 55:     /> 56: 57:   </form> 58:  </body> 59: </html> 

Binding to the DropDownList is very simple as Listing 8.12 demonstrates. First, you'll need an object to bind to ”in this example I use a SqlDataReader (lines 15 “19). After setting the DropDownList.DataSource I use the DropDownList.DataTextField attribute to set which field from the data source should be shown to the user in the list ” DropDownList.DataValueField . I use the DropDownList.DataValueField to set which field should be used as the DropDownList.Value .

In this example I also have set AutoPostBack to true and when the page is posted back to the server after a selected index change in the DropDownList , the Text and Value attributes are printed out to the page as seen in Figure 8.5.

Figure 8.5. After the page is posted back to the server the selected item details are printed out to the page.
graphics/08fig05.gif
only for RuBoard


Programming Data-Driven Web Applications with ASP. NET
Programming Data-Driven Web Applications with ASP.NET
ISBN: 0672321068
EAN: 2147483647
Year: 2000
Pages: 170

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net