访问数据网格视图中的行单元格时出错

时间:2016-04-23 05:12:49

标签: c# datagridview

这里,我在数据网格视图中添加了组合框和复选框。但是当我访问复选框或组合框时,它被给出了如下错误;

  

指数超出范围。必须是非负数且小于集合的大小。参数名称:index

填充数据后的数据网格视图如下所示

enter image description here

和后面的代码是,

private void button3_Click(object sender, EventArgs e)
 {
      DataGridViewRow roow=new DataGridViewRow();;
      int rcnt = dataGridView1.Rows.Count-1;
      int ccnt = dataGridView1.Rows[0].Cells.Count-1;
      for (int i = 1; i <= rcnt; i++)
      {
           DataGridViewCheckBoxCell ischecked= roow.Cells[ccnt] as DataGridViewCheckBoxCell;  
           if((bool)ischecked.Value==true)
           {
               for (int j = 1; j < ccnt; j++)
               {
                    dataGridView1.Rows[rcnt].Cells[ccnt].ReadOnly = true;
               }
           }
           ccnt--;
      }          
}

2 个答案:

答案 0 :(得分:0)

嗨,你必须在你的循环中使用0而不是1

来表达你的“i”和“j”

答案 1 :(得分:0)

试试这段代码:

 private void button1_Click(object sender, EventArgs e)
        {
            DataTable table = new DataTable();

            DataColumn col1 = new DataColumn("Name");
            DataColumn col2 = new DataColumn("Username");
            DataColumn col3 = new DataColumn("tr");
            col3.DataType = System.Type.GetType("System.Boolean");


            col1.DataType = System.Type.GetType("System.String");
            col2.DataType = System.Type.GetType("System.String");

            table.Columns.Add(col1);
            table.Columns.Add(col2);
            table.Columns.Add(col3);


            DataRow row = table.NewRow();
            row[col1] = "John";
            row[col2] = "John123";
            row[col3] = true ;

            table.Rows.Add(row);


             row = table.NewRow();
            row[col1] = "John1111";
            row[col2] = "John1225";
            row[col3] = false ;

            table.Rows.Add(row);

            row = table.NewRow();
            row[col1] = "John222";
            row[col2] = "John3333";
            row[col3] = true ;

            table.Rows.Add(row);


            row = table.NewRow();
            row[col1] = "John3333";
            row[col2] = "Jogggazg";
            row[col3] = false ;

            table.Rows.Add(row);


            dataGridView1.DataSource = table;
        }

 private void button2_Click(object sender, EventArgs e)
        {
            DataGridViewRow roow = new DataGridViewRow(); ;
            int rcnt = dataGridView1.Rows.Count - 2;
            int ccnt = dataGridView1.Rows[0].Cells.Count - 1;
            for (int i = 0; i <= rcnt; i++)
            {
                roow = dataGridView1.Rows[i];
                DataGridViewCheckBoxCell ischecked = roow.Cells[ccnt] as DataGridViewCheckBoxCell;
                if ( (bool)ischecked.Value == true)
                {
                    for (int j = 0; j <= ccnt; j++)
                    {
                        dataGridView1.Rows[rcnt].Cells[j].ReadOnly = true;
                    }
                }

            }          
        }