string  SelectedStr ="";
         for (int i = 0; i <= this.hobby.Items.Count; i++)
           {   
             if (this.hobby.Items[i].Selected == true)
                {     
        
        SelectedStr += hobby.Items[i].Value + ",";
        string Strhobby = "insert into stu_infor(username,hobby) values ('" + username.Text + "','" + SelectedStr + "')";
        OleDbCommand myCommInsertHobby = new OleDbCommand(Strhobby, myConn);
        myCommInsertHobby.ExecuteNonQuery();
               }
      
}
其中hobby是一个CheckBoxList控件的ID号。数据库连接的代码已经写好了。今天我调试程序的时候if (this.hobby.Items[i].Selected == true)老是报错,显示索引超出范围,必须为非负值并小于集合大小,我都不知道该咋个办了,还望各位大虾多多指教哟!

解决方案 »

  1.   

     for (int i = 0; i <this.hobby.Items.Count; i++)
    {}
      

  2.   

    page_load(。。)中的绑定
    {
    if(!IsPostBack)
    {
      //绑定this.hobby
    }
    }
      

  3.   

    i <= this.hobby.Items.Count把“<=” 改成“<” 试试
      

  4.   

    for (int i = 0; i < this.hobby.Items.Count; i++)
      

  5.   

    foreach(ListItem   item   in   CheckBoxList.Items) 

    }
    for (int i = 0; i < this.hobby.Items.Count; i++)
      {   
      if (this.hobby.Items[i].Selected)
      {   
       }
    }
    从0开始