Microsoft Knowledge Base Email Alertz

(314334) - This article demonstrates how to add static items and data-bound items to a DropDownList control. The sample in this article populates a DropDownList control with an initial item. Back to the top Requirements The following list outlines the...

Search KbAlertz

Advanced Search

Receive Microsoft Knowledge Base articles by E-Mail?

Every night we scan the Microsoft Knowledge Base. If technologies you're interested in are updated, we'll send you an e-mail. You only get one e-mail a day, and only when new articles are added.

Click here to create a
FREE account
Already have an account?
[Click here to Login]











Microsoft Knowledge Base Article

This article contents is Microsoft Copyrighted material.
©2005-©2007 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks

Article ID: 314334 - Last Review: April 19, 2007 - Revision: 5.4

How to add static items and results from data binding to a DropDownList control by using Visual C# .NET

This article was previously published under Q314334
For a Microsoft Visual C# .NET version of this article, see 312489  (http://kbalertz.com/Feedback.aspx?kbNumber=312489/ ) .

This article refers to the following Microsoft .NET Framework Class Library namespaces:
  • System.Data.SqlClient

On This Page

SUMMARY

This article demonstrates how to add static items and data-bound items to a DropDownList control. The sample in this article populates a DropDownList control with an initial item.

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
  • Microsoft Windows 2000 Professional, Microsoft Windows 2000 Server, Microsoft Windows 2000 Advanced Server, or Microsoft Windows XP
  • Microsoft .NET Framework
  • Microsoft Visual Studio .NET
  • Microsoft Internet Information Services (IIS)
  • Microsoft SQL Server

Create an ASP.NET Web application by using Visual Basic .NET

In the following steps, you create a new ASP.NET Web application that is named DDLSample.
  1. Open Microsoft Visual Studio .NET.
  2. On the File menu, point to New, and then click Project.
  3. In the New Project dialog box, click Visual Basic Projects under Project Types, and then click ASP.NET Web Application under Templates.
  4. In the Location box, replace WebApplication1 in the default URL with DDLSample. If you are using the local server, you can leave the server name as http://localhost so that the Location box displays http://localhost/DDLSample.

Create the sample

In the following steps, you create an .aspx page that contains a DropDownList Web server control. The DropDownList control is data bound to columns of the Authors table from the SQL Server Pubs database.
  1. Follow these steps to add a Web Form to the project:
    1. Right-click the project node in Solution Explorer, click Add, and then click Add Web Form.
    2. Name the .aspx page DropDown.aspx, and then click Open.
  2. Make sure that the page is open in Design view in the editor. Add a DropDownList control to the page. In the Properties pane, change the ID of the control to AuthorList.
  3. Add a Label control to the page after the DropDownList control. In the Properties pane, change the ID of the control to CurrentItem.
  4. Add a Button control to the page after the Label control. In the Properties pane, change the ID of the control to GetItem, and then change the Text property to Get Item.
  5. Right-click the page, and then click View Code. This opens the code-behind class file in the editor.
  6. Add the System.Data.SqlClient namespace to the code-behind class file as follows so that the sample code functions properly.
    Imports System.Data.SqlClient
    					
  7. Add the following code to the Page_Load event.
    Private Sub Page_Load(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles MyBase.Load
            If Not IsPostBack Then
                Dim myConn As SqlConnection = New SqlConnection("Server=localhost;" & _
                                                                "Database=Pubs;Integrated Security=SSPI")
                Dim myCmd As SqlCommand = New SqlCommand("SELECT au_id," & _
                                                         "au_lname FROM Authors", myConn)
    
    
                myConn.Open()
                Dim myReader As SqlDataReader = myCmd.ExecuteReader()
    
                'Set up the data binding.
                AuthorList.DataSource = myReader
                AuthorList.DataTextField = "au_lname"
                AuthorList.DataValueField = "au_id"
                AuthorList.DataBind()
    
                'Close the connection.
                myConn.Close()
                myReader.Close()
    
                'Add the item at the first position.
                AuthorList.Items.Insert(0, "<-- Select -->")
            End If
        End Sub
    					
    To use Integrated Security in the connect string, change the Web.config file for the application and set the impersonate attribute of the identity configuration element to true, as shown in the following example.
    <configuration>
      <system.web>
        <identity impersonate="true" />
      </system.web>
    </configuration>
    For more information about ASP.NET Impersonation, visit the following Microsoft Developer Network (MSDN) Web site:
    http://msdn2.microsoft.com/en-us/library/xh507fc5(vs.71).aspx (http://msdn2.microsoft.com/en-us/library/xh507fc5(vs.71).aspx)
  8. Modify the connection string as appropriate for your environment.
  9. Switch to the Design view in the editor for the .aspx page. Double-click GetItem. Add the following code to the GetItem_Click event in the code-behind class file.
    Private Sub GetItem_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles GetItem.Click
            Dim itemText As String = AuthorList.SelectedItem.Text
            Dim itemValue As String = AuthorList.SelectedItem.Value
            CurrentItem.Text = String.Format("Selected Text is {0}," & _
                                             "and Value is {1}", itemText, itemValue)
        End Sub
    					
  10. On the File menu, click Save All to save the Web Form and other associated project files.
  11. On the Build menu in the Visual Studio .NET IDE, click Build to build the project.
  12. In Solution Explorer, right-click the .aspx page, and then click View In Browser. Notice that the page opens in the browser and that the drop-down list box is populated with the initial data.
  13. Click an item in the drop-down list box. Notice that the CurrentItem Label control displays the item that you selected. Additionally, notice that the list retains the current position and the static entry.

Troubleshooting

  • You must place the code to add the static item to the ListItem collection of the control after the data binding code. If you do not add the code in this order, the list is re-created with the data binding code, which overwrites the static entry.
  • The sample code checks the IsPostBack property to prevent the list from being re-created. In addition, this code checks IsPostBack to retain the selected item in the current position of the list between round trips to the server.

REFERENCES

For more information about ASP.NET, and for a list of ASP.NET articles and resources, click the following article number to view the article in the Microsoft Knowledge Base:
305140  (http://kbalertz.com/Feedback.aspx?kbNumber=305140/ ) ASP.NET roadmap
For more information about ASP.NET server controls, click the following article number to view the article in the Microsoft Knowledge Base:
306459  (http://kbalertz.com/Feedback.aspx?kbNumber=306459/ ) ASP.NET server controls overview
For more information about data binding syntax and implementation with server controls in ASP.NET, click the following article number to view the article in the Microsoft Knowledge Base:
307860  (http://kbalertz.com/Feedback.aspx?kbNumber=307860/ ) ASP.NET data binding overview
For more information about the DropDownList class, visit the following MSDN Web site:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemWebUIWebControlsDropDownListClassTopic.asp (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemWebUIWebControlsDropDownListClassTopic.asp)
For information about how to work with ASP.NET, see the ASP.NET QuickStart tutorial at the following Microsoft Web site:
http://samples.gotdotnet.com/quickstart/aspplus/doc/default.aspx (http://samples.gotdotnet.com/quickstart/aspplus/doc/default.aspx)

APPLIES TO
  • Microsoft ASP.NET 1.1
  • Microsoft Visual Basic .NET 2003 Standard Edition
  • Microsoft ASP.NET 1.0
  • Microsoft Visual Basic .NET 2002 Standard Edition
Keywords: 
kbdatabinding kbhowtomaster kbservercontrols KB314334
       

Community Feedback System

Very often, it takes hours to solve a problem. Very often, you've looked high and low, and have tried a lot of solutions. When you finally found it, chances are, it was because someone else helped you. Here's your chance to give back. Use our community feedback tool to let others know what worked for you and what didn't.

Please also understand that the community feedback system is not warranted to be correct, it's simply a system that we've built to let people try and help each other. If something in a feedback response doesn't make sense to you, or you're not comfortable making changes that the feedback talks about (like registry edits), please consult a professional.

Thank you for using kbAlertz.com Feedback System.

-- Scott Cate