DataGridViewvalidation和更改单元格值

我想在validation时操作DataGridView中的单元格,这样如果用户输入的值对数据库无效,但很容易转换为有效数据,程序会将值更改为合适的值。

我可以正确validation我的值,但当我尝试将其更改为有效的东西时,我得到一个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 = rows [0] [“Batch”]的行; 没有做我期望它做的事情。

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

你需要做的是改变编辑控件中的值(记住不要取消事件)。 例如,对于DataGridViewTextBoxCell ,您将使用以下内容而不是有问题的行:

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

你会发现这解决了你的问题。

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