DataGridView验证和更改单元格值

Mic*_*cah 23 c# datagridview validating

我想在验证时操作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;
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

读取cell.Value = rows [0] ["Batch"]的行; 没有做我期望它做的事情.

Bra*_*ith 42

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

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

unit_List_2_GroupsDataGridView.EditingControl.Text = Convert.ToString(rows[0]["Batch"]);
Run Code Online (Sandbox Code Playgroud)

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


drw*_*ode 5

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