How can you set the selected item in an ASP.NET dropdown via the display text?(如何通过显示文本在 ASP.NET 下拉列表中设置所选项目?)
问题描述
我有一个通过数据绑定填充的 ASP.NET 下拉列表.我的文本与我要选择的列表项的显示文本相匹配.我显然不能使用 SelectedText(仅限 getter)而且我不知道索引,所以我不能使用 SelectedIndex.我目前正在通过遍历整个列表来选择项目,如下所示:
ASP:
代码:
ddItems.DataSource = myItemCollection;ddItems.DataTextField = "名称";ddItems.DataValueField = "Id";foreach(ddItems.Items 中的 ListItem 项目){if (item.Text == textToSelect){item.Selected = true;}}有没有办法在不遍历所有项目的情况下做到这一点?
你可以试试:
ddItems.Items.FindByText("Hello, World!").Selected = true;或者:
ddItems.SelectedValue = ddItems.Items.FindByText("Hello, World!").Value;请注意,如果您不确定是否存在与您的显示文本匹配的项目,您可能需要检查 FindByText() 的结果是否为 null.>
请注意,我在多选列表(例如 CheckBoxList)上使用第一种方法来添加额外的选择.我使用第二种方法来覆盖所有选择.
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?
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.
这篇关于如何通过显示文本在 ASP.NET 下拉列表中设置所选项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何通过显示文本在 ASP.NET 下拉列表中设置所选
基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
