2012-10-27 69 views
0

在我的datagridview中,我有4列,当用户给第一行一些值时,我想采用1st row 4th cell value and put it to the 2nd Row 3rd cell,就像我必须申请的所有行(请参阅图像)。在某些情况下,我只有2行,最大的我会有4行。将datagridview单元格值自动复制到同一个datagridview中的另一个单元格

它的工作方式如下,但当我测试2或3行它不工作..显然第三和第四是不存在的。

我该怎么办?有没有更好的方式做到这一点?

这里我编码最多4行。

private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e) 
     { 
      var value1 = dataGridView1.Rows[0].Cells[3].Value.ToString(); 
      dataGridView1.Rows[1].Cells[2].Value = value1; 

      var value2 = dataGridView1.Rows[1].Cells[3].Value.ToString(); 
      dataGridView1.Rows[2].Cells[2].Value = value2; 

      var value3 = dataGridView1.Rows[2].Cells[3].Value.ToString(); 
      dataGridView1.Rows[3].Cells[2].Value = value3; 
     } 

enter image description here

回答

2

这样的事情,你应该处理CellEndEdit,绝对不要硬编码行索引。

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) 
{ 
    if (e.ColumnIndex != 3) 
     return; 
    int nextRowIndex = e.RowIndex + 1; 
    int lastRowIndex = dataGridView1.Rows.Count - 1; 
    if (nextRowIndex <= lastRowIndex) 
    { 
     var value = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString(); 
     dataGridView1.Rows[nextRowIndex].Cells[2].Value = value; 
    } 
} 
+0

我有一个另外一个问题,我得到了验证细胞及细胞验证event..when我用你的方法或我的方法,并留在细胞中的光标,我尝试打开另一个文件..我'越来越错误'参数超出范围异常未处理'我必须调用cellEndEdit方法?谢谢。 – linguini

+0

我不明白!你如何打开一个文件,以及打开一个文件和你的DataGridView之间的关系是什么? – ehsanarc

+0

如果我将光标留在单元格中并通过打开文件打开另一个文件...我得到上述错误。如果删除光标并打开另一个文件..然后我没有得到任何错误。一旦我在单元格中输入了某些东西,它不会立即反映出来..我必须点击两次以反映..这是正常的? – linguini

相关问题