DropDownList不能选中的问题
来源:互联网 发布:数据透视表更新数据源 编辑:程序博客网 时间:2024/06/08 09:33
今天在做一个列表页面跳转到详细信息页面的时候,发现了一个很怪异的现象:通过地址栏的ID来匹配一个DropDownList的Value值,并让相应的项选中。先来看看我的代码:
if (DropDownList1.Items.Count > 0) { for (int i = 0; i < DropDownList1.Items.Count; i++) { if (DropDownList1.Items.FindByValue(id.ToString()) != null) { if (DropDownList1.Items.FindByValue(id.ToString()).Value == id.ToString()) { DropDownList1.SelectedIndex = i; break; } } } }
这是一个很简单的需求,但是我发现我的最终想要的结果总是不能出现。到底问题出在哪里呢?加入一些输出的语句看看:
if (DropDownList1.Items.Count > 0) { for (int i = 0; i < DropDownList1.Items.Count; i++) { if (DropDownList1.Items.FindByValue(id.ToString()) != null) { Debug.WriteLine("FindByValue(id.ToString()).Value:" + DropDownList1.Items.FindByValue(id.ToString()).Value); Debug.WriteLine("是否和指定的ID相等:" + DropDownList1.Items.FindByValue(id.ToString()).Value == id.ToString()); if (DropDownList1.Items.FindByValue(id.ToString()).Value == id.ToString()) { Debug.WriteLine("i:" + i.ToString()); DropDownList1.SelectedIndex = i; Debug.WriteLine("i:" + i.ToString()); Debug.WriteLine("DropDownList1.SelectedIndex:" + DropDownList1.SelectedIndex.ToString()); break; } } } }
浏览到这个页面后的输出结果:
看到了吧,i=0!也就是说,循环根本就没有起作用。FindByValue()是直接查找的。不需要来进行循环。因此我那种循环查找的办法根本就是错的。
修正的代码如下,另外在附上以前常用的一种办法:
//第一种选中DropDownList的方式(常见方式) if (DropDownList1.Items.Count > 0) { for (int i = 0; i < DropDownList1.Items.Count; i++) { if (DropDownList1.Items[i].Value == id.ToString()) { DropDownList1.SelectedIndex = i; break; } } } //第二种选中DropDownList的方式(不用循环) if (DropDownList1.Items.FindByValue(id.ToString()) != null) { if (DropDownList1.Items.FindByValue(id.ToString()).Value == id.ToString()) { DropDownList1.Items.FindByValue(id.ToString()).Selected = true; } }
示例代码下载
- DropDownList不能选中的问题
- GridView中DropDownList的选中值的问题
- 【C#】asp:DropDownList控件选中值不变的问题
- ExtJs 表格问题不能选中的解决方法
- 如何设置DropDownList的值被选中
- DropDownList中指定任意的选中项
- 动态设定DropDownList的选中值 转贴
- DropDownList中指定任意的选中项
- 动态设定DropDownList的选中值
- JS获取DropDownList 选中值的value
- js 取DropDownList选中的值
- 如何设置DropDownList的值被选中
- 如何获得DropDownlist选中的值
- 如何设置DropDownList的值被选中
- 关于dropdownlist的问题
- DropDownList绑定的问题
- 关于dropdownlist的问题
- QA:UICollectionView不能选中问题
- 基于Xen虚拟机的设计与实验
- hdu 1698 线段树(区间成段修改)
- 分析“关联”需仔细
- Eclipse打开Android应用工程的错误提示:invalid project description
- POJ 3509 Rotating Rings
- DropDownList不能选中的问题
- 一道C++面试题的误区
- TechCrunch:人人不是中国的Facebook
- 第5章 [BX]和loop指令 笔记
- C:2-8
- 两种方法点击客户区,移动对话框
- MYSQL 视图
- mysqlslow log分析
- 关于编程 鲜为人知的真相