设置“选择”HTML控件的选定值

时间:2023-01-26 14:29:09

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

如何使用ASP从代码隐藏文件中设置选择的HTML控件的值。NET和c#吗?

4 个解决方案

#1


21  

There are FindByText and FindByValue functions available:

有FindByText和FindByValue函数:

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

#2


3  

HTML:

HTML:

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

C#:

c#:

string fruitId = selUserFilterOptions.Value.ToString();

#3


1  

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


0  

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

您可以简单地使用以下代码获取选定的HTML选择选项的文本:

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

Select1 is the ID of your HTML select control.

Select1是HTML select控件的ID。

#1


21  

There are FindByText and FindByValue functions available:

有FindByText和FindByValue函数:

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

#2


3  

HTML:

HTML:

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

C#:

c#:

string fruitId = selUserFilterOptions.Value.ToString();

#3


1  

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


0  

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

您可以简单地使用以下代码获取选定的HTML选择选项的文本:

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

Select1 is the ID of your HTML select control.

Select1是HTML select控件的ID。