Set selected value of a 'Select' HTML control

68,455

Solution 1

There are FindByText and FindByValue functions available:

ListItem li = Select1.Items.FindByText("Three");
ListItem li = Select1.Items.FindByValue("3");
li.Selected = true;

Solution 2

HTML:

<select id="selUserFilterOptions" runat="server">
   <option value="1">apple</option>
   <option value="2">orange</option>
   <option value="3">strawberry</option>
</select>

C#:

string fruitId = selUserFilterOptions.Value.ToString();

Solution 3

Try this:

for (int i=0; i<=Select1.Items.Count - 1; i++)
{
    if (Select1.Items[i].Value = valueToSelect)
    {
        Select1.Items[i].Selected = true;
        // Try this too - http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlselect.selectedindex(v=VS.90).aspx
        //Select1.SelectedIndex = i;
    }
}
Share:
68,455
Amit
Author by

Amit

Updated on August 22, 2020

Comments

  • Amit
    Amit almost 4 years

    How can I set the selected value of a Select HTML control from a code-behind file using ASP.NET and C#?

  • Muhammad Akhtar
    Muhammad Akhtar about 13 years
    There is no need to iterate. there are methods given. check my answer.
  • Hari Pachuveetil
    Hari Pachuveetil about 13 years
    @Muhammad Akhtar: check the link from my comment in your answer
  • Muhammad Akhtar
    Muhammad Akhtar about 13 years
    Its .net 3.5 Framework Documentation. I have tested in .net 4.0. Could you check at your end?
  • Hari Pachuveetil
    Hari Pachuveetil about 13 years
    It's good even with v3.5 - msdn.microsoft.com/en-us/library/… .
  • aspiring
    aspiring almost 9 years
    Awesome! I was juggling with .SelectedIndex and Items properties.