DropDownList不能选中的问题

今天在做一个列表页面跳转到详细信息页面的时候,发现了一个很怪异的现象:通过地址栏的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;
                    }
                }
            }
        }

浏览到这个页面后的输出结果:

2011-05-03_230219

看到了吧,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;
            }
        }

示例代码下载

posted @ 2011-05-03 23:13  橘子西瓜  阅读(2037)  评论(9编辑  收藏  举报