我想为asp设置selecteditem.netdowndownlist控制以编程方式.
所以我想将一个值传递给dropdownlist控件来设置所选项目,其中项目的值等于传递的值.
Raa*_*aab 68
dropdownlist.ClearSelection(); //making sure the previous selection has been cleared
dropdownlist.Items.FindByValue(value).Selected = true;
Run Code Online (Sandbox Code Playgroud)
Adi*_*dil 32
您可以将其设置为SelectedValue要选择的值.如果您已经选择了项目,那么您应该清除选择,否则您将得到" 无法在DropDownList中选择多个项目 "错误.
dropdownlist.ClearSelection();
dropdownlist.SelectedValue = value;
Run Code Online (Sandbox Code Playgroud)
您还可以使用ListItemCollection.FindByText或ListItemCollection.FindByValue
dropdownlist.ClearSelection();
dropdownlist.Items.FindByValue(value).Selected = true;
Run Code Online (Sandbox Code Playgroud)
使用FindByValue方法在集合中搜索具有Value属性的ListItem,该属性包含value参数指定的值.此方法执行区分大小写和文化不敏感的比较.此方法不执行部分搜索或通配符搜索.如果使用此条件在集合中找不到项,则返回null,MSDN.
如果您希望您可能正在查找DropDownListListItem集合中不存在的文本/值,那么您必须检查是否获得了该ListItem对象null,FindByText或者FindByValue在访问Selected属性之前或之前.如果在返回null时尝试访问Selected,那么您将获得NullReferenceException.
ListItem listItem = dropdownlist.Items.FindByValue(value);
if(listItem != null)
{
dropdownlist.ClearSelection();
listItem.Selected = true;
}
Run Code Online (Sandbox Code Playgroud)
gif*_*tcv 25
您可以使用FindByValue方法在DropDownList中搜索具有与参数匹配的值的Item.
dropdownlist.ClearSelection();
dropdownlist.Items.FindByValue(value).Selected = true;
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用FindByText方法在DropDownList中搜索具有与参数匹配的Text的Item.
在使用FindByValue方法之前,不要忘记重置DropDownList,以便使用ClearSelection()方法不选择任何项目.它清除列表选择并将所有项的Selected属性设置为false.否则,您将收到以下异常.
"Cannot have multiple items selected in a DropDownList"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
218881 次 |
| 最近记录: |