如何通过显示文本在ASP.NET下拉菜单中设置所选项目? [英] How can you set the selected item in an ASP.NET dropdown via the display text?

查看:58
本文介绍了如何通过显示文本在ASP.NET下拉菜单中设置所选项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过数据绑定填写的ASP.NET下拉列表.我的文字与我要选择的列表项的显示文字匹配.我显然不能使用SelectedText(仅适用于getter),而且我不知道索引,因此无法使用SelectedIndex.我目前正在通过遍历整个列表来选择项目,如下所示:

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" /> 

代码:

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?

推荐答案

您可以尝试:

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

或者:

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

请注意,如果不确定是否存在与您的显示文本匹配的项目,则可能需要检查FindByText()的结果是否为null.

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.

请注意,我在多选列表上使用第一种方法,例如CheckBoxList来添加其他选择.我使用第二种方法来覆盖所有选择.

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.

这篇关于如何通过显示文本在ASP.NET下拉菜单中设置所选项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆