25

我想在验证时操作我的 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 = rows[0]["Batch"];的行 没有做我期望它做的事情。

4

2 回答 2

46

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

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

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

您应该会发现这可以解决您的问题。

于 2011-01-20T03:04:43.600 回答
5

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

于 2013-11-21T14:22:42.303 回答