dropdown lists in asp.net

G

Guest

I am trying to select the item in the dropdown list the matches a value
pulled from the database and set this matching item's selected property to
true so that it is the selected item in the combo box(dropdown list). How
would I do this in C#? It seems like it should be real easy but I can't make
it work. Thanks in advance
 
D

Dan Bass

if you're database value to match against is stored as a string, say:
string myDatabaseValue;

and your dropdownlist is defined as something like:
System.Web.UI.WebControls.DropDownList myDropdownList;

then you'd do the following in the Page_Load(...) function

private void Page_Load(object sender, System.EventArgs e)
{
if ( !Page.IsPostBack )
{
//
// code here to populate the myDatabaseValue string

//
// code here to populate the myDropdownList
programmatically

if ( myDropdownList.Items.Count > 0 )
{
try
{
myDropdownList.SelectedValue =
myDatabaseValue;
}
catch ( Exception )
{
myDropdownList.SelectedValue = 0;
}
}
} // endof !Page Postback
} // end of Page_Load


Hope that helps...
For an example on MSDN see:
http://msdn.microsoft.com/library/d...ontrolslistcontrolclassselectedvaluetopic.asp
(beware of line wraps)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top