2014-06-14 88 views
2

我有一个处理了CellValidating和RowValidating事件的datagridview。我的问题是,当我点击它,然后我改变主意,想要取消当前行的编辑时,这些验证方法不会让我这样做,如果它是第一行,它似乎在已经有一些有效行,但是当它是第一个时,它不会让我把焦点转移到别的东西上。允许用户取消datagridview中的编辑

所以我的问题是我怎样才能有验证和取消编辑datagridview行的能力?我不介意在编辑被取消时datagridview中的当前行是否丢失。

编辑: 这里是我的验证方法:

private void Neighbours_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) 
     { 
      if (e.ColumnIndex == 2) 
      { 
       int i = 0; 
       if (!int.TryParse(e.FormattedValue.ToString(), out i) || i <= 0) 
       { 
        e.Cancel = true; 
        Neighbours.Rows[e.RowIndex].ErrorText = "error"; 
       } 
      } 
     } 

private void Neighbours_RowValidating(object sender, DataGridViewCellCancelEventArgs e) 
     { 
      DataGridViewRow r = ((DataGridView)sender).Rows[e.RowIndex]; 
      int dist = 0; 
      if (r.Cells["NeighboursStop1"].Value == null || r.Cells["NeighboursStop1"].Value.ToString() == "" || r.Cells["NeighboursStop2"].Value == null || r.Cells["NeighboursStop2"].Value.ToString() == "") 
      { 
       e.Cancel = true; 
       r.ErrorText = "error"; 
      } 
      else if (r.Cells["NeighboursStop1"].Value.ToString() == r.Cells["NeighboursStop2"].Value.ToString()) 
      { 
       e.Cancel = true; 
       r.ErrorText = "error"; 
      } 
      else if(!int.TryParse(r.Cells["NeighboursDistance"].Value.ToString(), out dist)) 
      { 
       e.Cancel = true; 
       r.ErrorText = "error"; 
      } 
      else if (dist <= 0) 
      { 
       e.Cancel = true; 
       r.ErrorText = "error"; 
      } 
      else 
      { 
       r.ErrorText = ""; 
      } 
     } 

下面是它的外观,当它发生,如果我打Esc键,错误信息消失,但是当我尝试别的点击东西,RowValidation再次,我恰好回到这个状态:

error

EDIT2:我用数据表作为数据源这个datagridview的。

+0

提供一些代码和示例。 – codemonkey

+0

你用什么作为数据源? – Tuco

+0

我使用datatable作为数据源 – hynner

回答

2

我无法测试代码,但可以尝试以下方法吗?

private void Neighbours_RowValidating(object sender, DataGridViewCellCancelEventArgs e) 
    { 

     //Include this, check to see if the row is dirty 
     if (Neighbours.Rows[e.RowIndex] != null && !Neighbours.Rows[e.RowIndex].IsNewRow && Neighbours.IsCurrentRowDirty) 
     { 



     DataGridViewRow r = ((DataGridView)sender).Rows[e.RowIndex]; 
     int dist = 0; 
     if (r.Cells["NeighboursStop1"].Value == null || r.Cells["NeighboursStop1"].Value.ToString() == "" || r.Cells["NeighboursStop2"].Value == null || r.Cells["NeighboursStop2"].Value.ToString() == "") 
     { 
      e.Cancel = true; 
      r.ErrorText = "error"; 
     } 
     else if (r.Cells["NeighboursStop1"].Value.ToString() == r.Cells["NeighboursStop2"].Value.ToString()) 
     { 
      e.Cancel = true; 
      r.ErrorText = "error"; 
     } 
     else if(!int.TryParse(r.Cells["NeighboursDistance"].Value.ToString(), out dist)) 
     { 
      e.Cancel = true; 
      r.ErrorText = "error"; 
     } 
     else if (dist <= 0) 
     { 
      e.Cancel = true; 
      r.ErrorText = "error"; 
     } 
     else 
     { 
      r.ErrorText = ""; 
     } 
    } 

} 
+0

完美地工作,谢谢 – hynner