2011-01-20 174 views
22

我想操作DataGridView中的单元格进行验证时,如果用户输入的值对数据库无效,但很容易转换为有效数据,程序将将该值更改为适当的值。DataGridView验证和更改单元格值

我能够正确验证我的值,但是当我尝试将其更改为有效时,我得到一个DataError。这是我的代码:

 private void unit_List_2_GroupsDataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) 
    { 
     Console.WriteLine("Validating"); 
     DataGridViewColumn col = this.unit_List_2_GroupsDataGridView.Columns[e.ColumnIndex]; 
     DataGridViewCell cell = this.unit_List_2_GroupsDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex]; 
     if (col == this.batchDataGridViewTextBoxColumn && this.unit_List_2_GroupsDataGridView.IsCurrentCellInEditMode) 
     { 
      Console.WriteLine(" Batch Column"); 
      DataRow[] rows = label_EntryDataSet.viewJobBatchList.Select(String.Format("Job={0} AND Display='{1}'" 
       , comboBox1.SelectedValue, e.FormattedValue)); 
      if (rows.Length == 1) 
      { 
       Console.WriteLine("  Auto Completed item from list: {0}", rows[0]["Batch"]); 
       //e.Cancel = true; 
       cell.Value = rows[0]["Batch"]; 
       //this.unit_List_2_GroupsDataGridView.EndEdit(); 
      } 
      else 
      { 
       Console.WriteLine("  No Autocomplete!"); 
       int i = 0; 
       if (!int.TryParse(e.FormattedValue.ToString(), out i)) 
       { 
        Console.WriteLine("   Not an integer either"); 
        e.Cancel = true; 
       } 
      } 
     } 
    } 

读取cell.Value行=行[0] [ “批量”];没有做我期望的事情。

+0

请发布确切的错误消息,并指出哪一行代码被提及。 – David 2011-01-20 02:50:46

回答

39

CellValidating事件发生在DataGridView离开编辑模式之前;这是涉及编辑控件的事件(DataGridView.EditingControl)。您不应该尝试更改此事件的处理程序中的单元格值,因为除非您取消该事件(在这种情况下用户处于编辑模式),否则单元格值将设置为紧跟在该事件之后的编辑控件的值事件结束。因此,这撤消了您在处理程序中执行的任何操作。

你必须做的是改变编辑控件的值(记住不要取消事件)。例如,对于一个DataGridViewTextBoxCell,你可以使用以下的,而不是你的问题的行:

unit_List_2_GroupsDataGridView.EditingControl.Text = Convert.ToString(rows[0]["Batch"]); 

你应该找到解决您的问题。

+0

这确实解决了我的问题。非常感谢你。 – Micah 2011-01-20 20:41:21

3

通常,无论何时需要转换/更改单元格中的值,最好使用CellParsing事件。在该事件中,您可以通过设置单元格或行的ErrorText值来指示用户的值无效。

相关问题