aspx thread: Re: How do you preselect a value on dropdown or Listbox using ASP.NET code ?
Hi, this is the sample.
I am displaying a form for customer billing information updating (the
customer billing information is already in the database and the user wants
to update it). So when I display the countries DropDownList I want the
customer's country to appear selected:
// Bind the countries to the DropDownList.
dropDownList.DataSource = myCustomersDB.GetCountries().Tables
[0].DefaultView;
dropDownList.DataTextField = "Name";
dropDownList.DataValueField = "CountryId";
dropDownList.DataBind();
// Get the customer billing information.
DataRow customerDataRow = myCustomersDB.GetCustomer(customerId).Tables
[0].Rows[0];
// Determine the index of customer's country in the DropDownList. We have
// to create a ListItem to test for the index. The ListItem.Text property
// is empty since I don't store the BillingContryName in the Customers
// table. The ListItem.Value property is assigned to
// customerDataRow["BillingCountryId"].
int index = dropDownList.Items.IndexOf(new ListItem("", customerDataRow
["BillingCountryId"].ToString()));
// Set the SelectedIndex of the DropDownList.
dropDownList.SelectedIndex = index;
So I get the index in the DropDownList that corresponds with the
BillingCountryId stored in the database, and then I make that index
selected.
I think in ASP.NET Beta 2 this could be done much easily:
dropDownList.Items.FindByValue(customerDataRow["BillingCountryId"].ToString
()).Selected = true;
But I haven't test it yet. As a matter of fact, I'm downloading Beta 2 at
this very moment.
Hope this helps ;-)
---------------------------------------------
Adolfo Gutierrez
adolfo.gutierrez@a...
Audiotronics.es - La tienda de la informática
http://www.audiotronics.es
> can some body help me in preselecting an item from the database to a
value
> in the list box which is databinded using values from the same database.
>
> Example:
>
> Let us say i am searching for a customer information based on
customerid.
> I get the customer state based on customerid as 'VA' i would like to
> preselect this in a dropdown list of states once the page is loaded. can
> some body supply some code.
>
> thx in advance
>