即使单元格值未通过验证,我如何从dataGridView单元格移动方式?

时间:2012-07-10 10:02:34

标签: c# winforms c#-4.0 datagridview

我正在验证未绑定的dataGridView控件中的单元格值,但我不喜欢这种行为。

当在单元格中输入无效值时,我无法离开该单元格,就可以了。当我从单元格中清除无效数据并将其留空或空白时,我仍然无法离开单元格并且不喜欢它。即使我按Escape键撤消我在单元格中输入的无效数据,在输入该特定单元格中的有效值之前,也无法移动到dataGridView中的任何其他单元格。这意味着我无法取消行的输入,例如缺少单列值。

要离开单元格,我必须键入至少0(零),但我不想这样做,我希望能够说好,让我只是进入整个记录,或者将单元格值重置为空,突出显示,移动到另一个单元格,然后稍后返回。

private void dataGridViewSales_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
            {
                switch (this.dataGridViewSales.Columns[e.ColumnIndex].Name)
                {   
                    case "Qty":
                        {
                            decimal qty;

                            if (!decimal.TryParse(e.FormattedValue.ToString(), out qty))
                            {
                                e.Cancel = true;
                                this.dataGridViewSales.Rows[e.RowIndex].ErrorText = "The quantity sold must be a numeric value";
                                dataGridViewSales.EditingControl.BackColor = Color.Red;
                            }
                        }
                        break;
                }
            }

2 个答案:

答案 0 :(得分:1)

谢谢,这样做了

if (this.dataGridViewSales.Rows[e.RowIndex].IsNewRow || string.IsNullOrEmpty(e.FormattedValue.ToString()))
    {
    return;
    }
    else
    {
    e.Cancel = true;
    }

答案 1 :(得分:0)

if (!string.IsNullOrEmpty(e.FormattedValue.ToString()) &&
    !decimal.TryParse(e.FormattedValue.ToString(), out qty))
{
    e.Cancel = true;
    ...
}
相关问题