How can I set the selected value of a Select HTML control from a code-behind file using ASP.NET and C#?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
There are FindByText and FindByValue functions available:
ListItem li = Select1.Items.FindByText("Three");
ListItem li = Select1.Items.FindByValue("3");
li.Selected = true;
Method 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();
Method 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;
}
}
Method 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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0