Set selected value of a 'Select' HTML cont

2020-02-12 00:02发布

问题:

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

回答1:

There are FindByText and FindByValue functions available:

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


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


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


回答4:

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.