Amit
Amit

Reputation: 7035

Set selected value of a 'Select' HTML control

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

Upvotes: 15

Views: 75425

Answers (4)

RSB
RSB

Reputation: 359

You can simply use the following code to get the text of the selected option of HTML Select:

var selectedText = Select1.Items[Select1.SelectedIndex].Text.Trim();

Select1 is the ID of your HTML select control.

Upvotes: 0

Muhammad Akhtar
Muhammad Akhtar

Reputation: 52241

There are FindByText and FindByValue functions available:

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

Upvotes: 24

Shanker Kana
Shanker Kana

Reputation: 49

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();

Upvotes: 3

Hari Pachuveetil
Hari Pachuveetil

Reputation: 10374

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;
    }
}

Upvotes: 1

Related Questions