joaquin112
New Member
Hi I want to make an item selected in ASP
ropDownList 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=;Database=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>After you bind your dropdown do the following:<BR><BR>category.Items.FindByValue(15).selected = true<BR><BR>])ryYou 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.
