How to make an item selected in ASP:DropDownList ?

Results 1 to 3 of 3

Thread: How to make an item selected in ASP:DropDownList ?

  1. #1
    Join Date
    Dec 1969

    Default How to make an item selected in ASP:DropDownList ?

    Hi I want to make an item selected in ASP:DropDownList based on what ID is retrieved from the Database. <BR><BR>For example, I have a list of categories bind to a DropDownList: <BR>myConnection = New SQLConnection("Server=Localhost;uid=sa;pwd=;Databa se=Northwind") <BR>myCommand = New SQLCommand("Select CategoryID, CategoryName from Categories", myConnection) <BR>myConnection.Open() <BR>category.DataSource = myCommand.ExecuteReader() <BR>category.DataTextField = "CategoryName" <BR>category.DataValueField = "CategoryID" <BR>category.DataBind() <BR>myConnection.Close() <BR><BR>How do I make the item selected if the CategoryID retrieved from the Database is 15 ? <BR><BR>Thanks <BR>

  2. #2
    Join Date
    Dec 1969

    Default FindByValue

    After you bind your dropdown do the following:<BR><BR>category.Items.FindByValue(15).s elected = true<BR><BR>])ry

  3. #3
    Join Date
    Dec 1969

    Default RE: FindByValue

    You can select which item is selected by the SelectedIndex.<BR>If your category ids are in numerical order(ex. 1-15) you could set the SelectedIndex to the CategoryID -1 (you need to subtract 1 because the DropDownList starts at 0)<BR><BR>If the categories are not in numerical order, you could use an enum that will return a int when compared against a string. Then you could use that int for the SelectedIndex.<BR> <BR>C# Ex.<BR>1)create an enum that list the 50 states in order<BR>enum States{ Alabama = 1, Alaska, Arizona, ...}<BR><BR>2) Get the integer equivalent for the string, in this example pState is a parameter returned by a stored procedure that contains the value of the "State" field in the database<BR>int intState = (int)parse(typeof(Enums.States),pState.Value.ToStr ing());<BR><BR>so, "Alabama" would return 1<BR> <BR>3) Finally, Set the SelectedIndex for the DropDownList(ddlStates) to the int returned by the previous statement.<BR>this.ddlStates.SelectedIndex = intState;<BR><BR>hope this helps.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts