web-dev-qa-db-fra.com

Définir la valeur sélectionnée d'un contrôle HTML 'Select'

Comment définir la valeur sélectionnée d'un contrôle HTML Select à partir d'un fichier code-behind utilisant ASP.NET et C #?

13
Amit

Il existe FindByText et FindByValue fonctions disponibles: 

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

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
Shanker Kana

Essaye ça:

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;
    }
}
1
Floyd Pink

Vous pouvez simplement utiliser le code suivant pour obtenir le texte de l'option sélectionnée de HTML Select:

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

Select1 est l'ID de votre contrôle de sélection HTML.

0
RSB