As you probably know, DropDownList and ListBox have the same base class, ListControl, and both use ListItem to add Items to their collections. The difference between both controls is that DropDownList can have just one Item selected, while ListControl can have many Items selected at the same time.
At runtime, you have two different ways to select items in both controls. You can set the Selected property of the ListItem you want to select to true, or set the SelectedIndex property of the controls to the index of the ListItem you want to select. Both are valid, but for the DropDownList the second one is better than the other because there are no checks to avoid multiple selection. If you have set more than one ListItem.Selected property to true, you'll get an Exception when the control is rendered.
Conclusion.
While you are working with DropDownList, try not to use the Selected property of the ListItems to change the selection of the control. If you want to select one Item, get the Item with one of this methods (ListItemCollection.FindByText(string Text) or ListItemCollection.FindByValue(string value)) and then set the SelectedIndex of the DropDownList to the result of the method ListItemCollection.IndexOf(ListItem item). Doing this way you won't have any problem.
原来的代码:
/// <summary>
/// 根据值选择下拉选项
/// </summary>
/// <param name="val"></param>
public void SelectItemByValue (ListControl ltc,string val)
{
if (ltc.Items.Count==0)
return;
ltc.SelectedItem.Selected=false;
foreach(ListItem item in ltc.Items)
{
if (item.Value.Trim().ToUpper()==val.Trim().ToUpper())
{
item.Selected=true;
return;
}
}
}
修改后的代码:
protected void SelectItemByValue(ListControl ltc,string value)
{
ListItem lst = ltc.Items.FindByValue(value);
if (lst != null)
{
ltc.SelectedIndex = ltc.Items.IndexOf(lst);
}
}
英文转自-http://blogs.clearscreen.com/enadan/archive/2006/02/13/2794.aspx
posted @ 2007-11-08 15:30
jww 阅读(275)
评论(0) 编辑 收藏 网摘 所属分类:
.NET点滴