Solution — "Cannot have multiple items selected in a DropDownList."

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点滴

标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2008-01-11 08:24 编辑过
Google站内搜索


China-pub 计算机图书网上专卖店!6.5万品种 2-8折!
近千种 9-95 新二手计算图书火热销售中!

相关文章:

相关链接: