how to select with DropDownList.text

前端 未结 8 2369
逝去的感伤
逝去的感伤 2020-12-28 21:56

I am working on an Asp.NET project and I am trying to set the selected value of a dropdown list with a text property. For example i have i.e an item in the dropdown list wit

相关标签:
8条回答
  • 2020-12-28 22:31

    I think the SelectedValue property should do what you need.

    0 讨论(0)
  • 2020-12-28 22:34
    drpFunction.SelectedValue = drpFunction.Items.FindByText(t).Value;
    

    This is better way to select text. By ioden's way it will show an error

    "Multiple Items Cannot be selected in DropDownList"

    0 讨论(0)
  • 2020-12-28 22:36
    protected void Page_Load(object sender, EventArgs e)
    {
        string t = "test";
        drpFunction.SelectedValue = t;
    }
    

    The SelectedValue property can be used to select an item in the list control by setting it with the value of the item. However, an exception will be thrown during postback if the the selected value doesn't match the list of values in the dropdown list.

    http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.selectedvalue(v=vs.110).aspx

    0 讨论(0)
  • 2020-12-28 22:38

    This Link might help you

    public static void SelectText(this DropDownList bob, string text)
    {
        try
        {
            if (bob.SelectedIndex >= 0)
                bob.Items[bob.SelectedIndex].Selected = false;
            bob.Items.FindByText(text).Selected = true;
        }
        catch
        {
            throw new GenericDropDownListException("value", text);
        }
    }
    
    0 讨论(0)
  • 2020-12-28 22:39
     string t = "test";
     drpFunction.ClearSelection();
     drpFunction.Items.FindByText(t).Selected = true;
    
    0 讨论(0)
  • 2020-12-28 22:42

    This works in Web

    ListItem li=new ListItem(); 
    
    li.Text="Stringxyz";
    li.Value="Stringxyz";       // Create object of item first and find its index.
    
    DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(li);
    

    This also works fine.

    0 讨论(0)
提交回复
热议问题