DrowDownList的SelectedIndex如何确定?
今天在首页上发现这篇文章关于ASP.NET控件DropDownList控件的问题 ,觉得有意思,于是自己试了一下,结果还真如文章作者所说。
于是我用reflector查看了一下DropDownList的源码,在LoadPostData方法中我发现了这样的代码:
SetPostDataSelection(设定选定Item):
FindByValueInternal方法的代码如下:
根据以上两个方法的源码我发现DropDownList的SelectedIndex的确定与ListItem的Value属性的值有关。
DropDownList根据ListItem的Value属性的值来确定SelectedIndex属性。DropDownList在确定SelectedIndex属性的值时会遍历Items中的ListItem,查找与指定值想对应的ListItem,每次遍历递增索引值。
如下例:
当选中西瓜时,DropDownList会遍历Items,根据Value来确定SelectedIndex,然而香蕉的Value与西瓜的一样,也就是说,当遍历到香蕉时,DropDownList会认为你选择的是香蕉,FindByValueInteral中num1值为0,从而SelectedIndex=0了。
于是我用reflector查看了一下DropDownList的源码,在LoadPostData方法中我发现了这样的代码:
protected virtual bool LoadPostData(string postDataKey, NameValueCollection postCollection) { string[] textArray1 = postCollection.GetValues(postDataKey); this.EnsureDataBound(); if (textArray1 != null) { int num1 = this.Items.FindByValueInternal(textArray1[0], false); if (this.SelectedIndex != num1) { base.SetPostDataSelection(num1); return true; } } return false; } |
protected void SetPostDataSelection(int selectedIndex) { if ((this.Items.Count != 0) && (selectedIndex < this.Items.Count)) { this.ClearSelection(); if (selectedIndex >= 0) { this.Items[selectedIndex].Selected = true; } } } |
FindByValueInternal方法的代码如下:
internal int FindByValueInternal(string value, bool includeDisabled) { int num1 = 0; foreach (ListItem item1 in this.listItems) { if (item1.Value.Equals(value) && (includeDisabled || item1.Enabled)) { return num1; } num1++; } return -1; } |
DropDownList根据ListItem的Value属性的值来确定SelectedIndex属性。DropDownList在确定SelectedIndex属性的值时会遍历Items中的ListItem,查找与指定值想对应的ListItem,每次遍历递增索引值。
如下例:
Value | Text |
0 | 香蕉 |
1 | 苹果 |
2 | 桔子 |
0 | 西瓜 |
1 | 葡萄 |
当选中西瓜时,DropDownList会遍历Items,根据Value来确定SelectedIndex,然而香蕉的Value与西瓜的一样,也就是说,当遍历到香蕉时,DropDownList会认为你选择的是香蕉,FindByValueInteral中num1值为0,从而SelectedIndex=0了。