How can I set the selected value of a Select
HTML control开发者_高级运维 from a code-behind file using ASP.NET and C#?
There are FindByText
and FindByValue
functions available:
ListItem li = Select1.Items.FindByText("Three");
ListItem li = Select1.Items.FindByValue("3");
li.Selected = true;
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();
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;
}
}
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.
精彩评论