Bharathi Dasan
Bharathi Dasan

Reputation: 59

how to set the default value to the drop down list in C#?

DataSet dsCurrency = new DataSet();               
dsCurrency = ParamCurrency.SelectCurrencys();
ddCurrencyField.DataSource = dsCurrency;
ddCurrencyField.DataTextField = "CurrencyName";
ddCurrencyField.DataValueField ="CurrencyCode";               
ddCurrencyField.DataBind();

How to select a default value to the dropdownlist control using C#?

Upvotes: 1

Views: 5090

Answers (3)

Chinthana
Chinthana

Reputation: 1567

I assume in your datasource object (dsCurrency) is not parsing the default value for the dropdown. So first you will have to add the default item. After binding the datasource do the following.

ddCurrencyField.Items.Insert(0, new ListItem("-- Select --",0));

With the above code you will have a default/first item selected as "--Select--". If it does not select the first item then simply set the SelectedIndex to 0.

There are 2 ways to set the default item after populating a dropdown.

  1. you can use the "SelectedValue" property
  2. you can use the "SelectedIndex" property

Most of the code samples are given in the previous answers. But I prefer to use the "FindByValue" method.

ddCurrencyField.SelectedIndex = ddCurrencyField.Items.IndexOf(ddCurrencyField.Items.FindByValue(myValue));

If you want to write a safe code please use the second option.

Upvotes: 2

Phiter
Phiter

Reputation: 14992

If this dropdown list is a combobox, use this:

ddCurrencyField.SelectedIndex = ddCurrencyField.Items.IndexOf("Wanted Value");

Upvotes: 0

Mohammad Arshad Alam
Mohammad Arshad Alam

Reputation: 9862

If you know the value will exist:

ddCurrencyField.FindItemByText("YourDefaultText").Selected = true;

else

ListItem selectedListItem = ddCurrencyField.Items.FindItemByText("YourDefaultText");

if (selectedListItem != null)
{
    selectedListItem.Selected = true;
};

You can also find item by value :

ListItem selectedListItem = ddCurrencyField.Items.FindByValue("YourDefaultValue");

    if (selectedListItem != null)
    {
        selectedListItem.Selected = true;
    };

Upvotes: 1

Related Questions