【问题标题】:DataGridView Validation & Changing Cell ValueDataGridView 验证和更改单元格值
【发布时间】:2013-11-21 22:22:42
【问题描述】:

我想在我的 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"]; 的行没有按照我的预期进行。

【问题讨论】:

  • 请发布确切的错误信息并指出提到了哪一行代码。

标签: c# datagridview validating


【解决方案1】:

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

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

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

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

【讨论】:

  • 您的回复很棒,为我节省了大量时间。有没有办法从 CellValidating 事件中更改 dgv 单元格样式格式和单元格标记?到目前为止,我已经尝试了一些方法,但没有找到答案。
  • @SteveRehling 您应该可以随时设置Tag 属性。我没有尝试更改CellValidating 事件中的单元格样式;我的建议是将此代码放在CellValueChanged 事件中(如果可能的话)。
  • 如果你的列不是String类型,在比较之前一定要toString()这个值。更改编辑值时,请务必将此类型设为字符串。
  • 感谢布拉德利史密斯,太好了,多年来我一直在寻找解决这种情况的最佳方法。
【解决方案2】:

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

【讨论】:

  • 这个答案解决了我的特殊问题,但仍然需要处理 CellValidating,因为如果用户的输入是垃圾并且我在处理 CellParsing 时无法更正它,我仍然希望将它们保持在编辑状态模式(在处理 CellParsing 时无法完成)。值得注意的是,在这种情况下,CellValidating 会在 CellParsing 之前引发。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-08
  • 2012-02-03
  • 1970-01-01
相关资源
最近更新 更多