我有一个gridview,里面有一个dropdownlist控件和增加删除按钮。
我要完成的效果是通过选择Dropdownlist的选项,将值加入一个checkboxlist里面。我的代码如下,可是有错误。
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
           
        int index = ((GridViewRow)(((DropDownList)sender).NamingContainer)).RowIndex;
        DropDownList ddl = GridView1.Rows[index].Cells[2].FindControl("DropDownList1") as DropDownList;
        int n = ddl.Items.Count;
        for (int i = 0; i < n; i++)
        {   if(ddl.Items[i].Selected){            CheckBoxList1.Items[index].Value = ((DropDownList)sender).SelectedValue;
            CheckBoxList1.Items.Add(ddl.Items[i].Value);
        }
        }     
    }
异常详细信息: System.ArgumentOutOfRangeException: 索引超出范围。必须为非负值并小于集合大小。
参数名: index

解决方案 »

  1.   

    调试,越界了,看看[index]之类的和for循环中是否存在越界
      

  2.   

    ((GridViewRow)(((DropDownList)sender).NamingContainer)).RowIndex;
    取得的不是你想要的行索引 你可以调试下看看。
      

  3.   

    你的CheckBoxList1是直接操作?添加内容的话应该是Add方法
      

  4.   

    ((GridViewRow)(((DropDownList)sender).NamingContainer)).RowIndex;
    取得的不是你想要的行索引很可能是-1, 你可以调试下看看。
      

  5.   

    如何获取我当前选择的dropdownlist行的索引呢? 
      

  6.   


    我调试过了,index的值就是从0开始的。
      

  7.   

    应该是你这一块越界了if(ddl.Items[i].Selected)
    {  CheckBoxList1.Items[index].Value = ((DropDownList)sender).SelectedValue;
      CheckBoxList1.Items.Add(ddl.Items[i].Value);
    }
    假设checkboxlist里没有项,你这里开始设置CheckBoxList1.Items[index].Value的时候,一定索引越界
      

  8.   

    程序是在什么时候发生错误啊,是根本没运行起来,还是运行起来后选择Dropdownlist导致错误呢
    错误停在哪一句?另外   CheckBoxList1里面的项和Dropdownlist1的项内容一样多么应该是这里的错:
    CheckBoxList1.Items[index].Value = ((DropDownList)sender).SelectedValue;
      CheckBoxList1.Items.Add(ddl.Items[i].Value);
      

  9.   


    希望看到是否如9L猜测 LZ要调试下具体哪里啊,,
      

  10.   

    我觉得既然只有一个dropdowanlist,为什么不直接将其selectedvalue取出,添加到checkboxlist里面
      

  11.   


    我的gridview里面有添加按钮啊,添加了以后就有另外一个dropdowanlist了。 
    所以我想实现的是每行的Dropdownlist添加入相应的checkboxl的ITEM里面。