0

我正在验证未绑定的 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;
                }
            }
4

2 回答 2

1

谢谢,是这样弄的

if (this.dataGridViewSales.Rows[e.RowIndex].IsNewRow || string.IsNullOrEmpty(e.FormattedValue.ToString()))
    {
    return;
    }
    else
    {
    e.Cancel = true;
    }
于 2012-07-10T11:41:52.730 回答
0
if (!string.IsNullOrEmpty(e.FormattedValue.ToString()) &&
    !decimal.TryParse(e.FormattedValue.ToString(), out qty))
{
    e.Cancel = true;
    ...
}
于 2012-07-10T11:19:28.437 回答