How can you set the selected item in an ASP.NET dr

2019-02-06 05:46发布

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 SelectedText (getter only) and I don't know the index, so I can't use SelectedIndex. I currently am selecting the item by iterating through the entire list, as show below:

ASP:

<asp:DropDownList ID="ddItems" runat="server" /> 

Code:

ddItems.DataSource = myItemCollection;
ddItems.DataTextField = "Name";
ddItems.DataValueField = "Id";

foreach (ListItem item in ddItems.Items)
{
    if (item.Text == textToSelect)
    {
        item.Selected = true;
    }
}

Is there a way to do this without iterating through all the items?

4条回答
2楼-- · 2019-02-06 06:05

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;
}
查看更多
时光不老,我们不散
3楼-- · 2019-02-06 06:12

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.

查看更多
We Are One
4楼-- · 2019-02-06 06:12

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;
    }
}
查看更多
混吃等死
5楼-- · 2019-02-06 06:26

Its working fine ..

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

Or

drplistcountry.ClearSelection();
drplistcountry.SelectedIndex = 
drplistcountry.Items.IndexOf(drplistcountry.Items.FindByText("--Select--"));
查看更多
登录 后发表回答