How can you set the selected item in an ASP.NET dropdown via the display text?

前端 未结 4 1468
太阳男子
太阳男子 2020-12-09 16:54

I have an ASP.NET dropdown that I\'ve filled via databinding. I have the text that matches the display text for the listitem I want to be selected. I obviously can\'t use Se

相关标签:
4条回答
  • 2020-12-09 17:02

    If you have to select dropdown selected item text for multiple dropdown cases then use this way.

    // Call Method
    SelectDropdownItemByText(ddlDropdown.Items.FindByText("test"));
    
    // Define method
    public void SelectDropdownItemByText(ListItem item)
    {
        if (item != null)
        {
            item.Selected = true;
        }
    }
    
    0 讨论(0)
  • 2020-12-09 17:04

    You can try:

    ddItems.Items.FindByText("Hello, World!").Selected = true;
    

    Or:

    ddItems.SelectedValue = ddItems.Items.FindByText("Hello, World!").Value;
    

    Note that, if you are not certain that an items exists matching your display text, you may need to check the results of FindByText() for null.

    Note that I use the first approach on a multiple-select list, such as a CheckBoxList to add an additional selection. I use the second approach to override all selections.

    0 讨论(0)
  • 2020-12-09 17:17

    Its working fine ..

    drplistcountry.SelectedIndex = 
    drplistcountry.Items.IndexOf(drplistcountry.Items.FindByText("--Select--"));
    

    Or

    drplistcountry.ClearSelection();
    drplistcountry.SelectedIndex = 
    drplistcountry.Items.IndexOf(drplistcountry.Items.FindByText("--Select--"));
    
    0 讨论(0)
  • 2020-12-09 17:18

    Use the FindByText method of the ListItemCollection class, such as:

    ListItem itemToSelect = ddlItems.Items.FindByText("some text to match");
    
    if(itemToSelect != null)
    {
        itemToSelect.Selected = true;
    }
    
    0 讨论(0)
提交回复
热议问题