以编程方式设置下拉列表 selecteditem [英] Setting dropdownlist selecteditem programmatically
问题描述
我想以编程方式为 ASP.Net 下拉列表控件设置 selecteditem
属性.
I want to set the selecteditem
attribute for an ASP.Net dropdownlist control programmatically.
所以我想向下拉列表控件传递一个值来设置选中的项目,其中项目等于传递的值.
So I want to pass a value to the dropdownlist control to set the selected item where the item is equal to the passed value.
推荐答案
假设列表已经是数据绑定的,您只需在下拉列表中设置 SelectedValue
属性即可.
Assuming the list is already data bound you can simply set the SelectedValue
property on your dropdown list.
list.DataSource = GetListItems(); // <-- Get your data from somewhere.
list.DataValueField = "ValueProperty";
list.DataTextField = "TextProperty";
list.DataBind();
list.SelectedValue = myValue.ToString();
myValue
变量的值需要存在于控件数据绑定的 DataValueField
内指定的属性中.
The value of the myValue
variable would need to exist in the property specified within the DataValueField
in your controls databinding.
更新:如果 myValue
的值不作为下拉列表选项的值存在,它将默认选择下拉列表中的第一个选项.
UPDATE:
If the value of myValue
doesn't exist as a value with the dropdown list options it will default to select the first option in the dropdown list.
这篇关于以编程方式设置下拉列表 selecteditem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!