private void Page_Load(object sender, System.EventArgs e)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
int i = this.drpRuleType.SelectedIndex;
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
把它放到一个简单web页面中直接运行是没有任何问题的,但如果是在调试状态,你会发现一个比较有趣的bug,把断点设置到this.drpRuleType.Items.FindByValue(this.txtValue.Text.Trim()).Selected = true;当程序运行到这里时将鼠标移到上一行代码上查看一下this.drpRuleType.SelectedIndex,发现此时的值是0(不是设置为-1了吗,好像不管用哦),继续向下运行,著名的黄页出现了
,错误为:“DropDownList 不能有多个项被选定。”什么原因呢?
经过认真地调试及.NET源码的帮助,发现了这个问题,请看DropDownList的SelectedIndex属性源码实现:
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
看到了吧,在取SelectedIndex时自动进行了判断,只要有数据那么Selected的值就肯定大于等于0,所以我们在查看时发现设置成-1是无效的,它会自动改为0,另外它还做了另外一部操作this.Items[0].Selected = true;这个也就是直接导致Exception产生的原因(我只是想看看SelectedIndex它就把Item[0]的Selected值给改了...),所以大家在调试代码时就千万要小心了(不该看的东西就表看,否则后果很严重D~)
注:我们暂且先不谈这句代码的必要性this.drpRuleType.SelectedIndex = -1;只是为了说明的需要。