日期:2014-05-18  浏览次数:21139 次

c#问题求解(附有代码) 索引超出范围
private void button2_Click(object sender, EventArgs e)
  {  
  foreach (DataGridViewRow row in dgv_Caddie.Rows)
  {
  if ((bool)row.Cells["stunumber"].FormattedValue == true)
  {
  if (row.Cells["stuid"].Value != null && row.Cells["stuname"].Value != null)
  {
  for (int i = 0; i <= this.dataGridView1.Rows.Count; i++)
  {
11 this.dataGridView1.Rows[i].Cells[0].Value = row.Cells["stuid"].Value;
12 this.dataGridView1.Rows[i].Cells[1].Value = row.Cells["stuname"].Value;
  }
  }
  }
  }
  }
11,12显示索引超出范围。必须为非负值并小于集合大小;求高手解答

------解决方案--------------------
C# code
for(int i=0;i<dgv_Caddie.Rows.Count)
{
    if ((bool)dgv_Caddie.Rows[i].Cells["stunumber"].FormattedValue == false)
      return;
  if (dgv_Caddie.Rows[i].Cells["stuid"].Value == null || dgv_Caddie.Rows[i].Cells["stuname"].Value == null)
          return;
  if(i>=this.dataGridView1.Rows.Count)
      return;
  this.dataGridView1.Rows[i].Cells[0].Value = dgv_Caddie.Rows[i].Cells["stuid"].Value;
  this.dataGridView1.Rows[i].Cells[1].Value = dgv_Caddie.Rows[i].Cells["stuname"].Value;
}