DataGridView 验证用户输入

DataGridView validate user input

我有一个以这种方式填充对象值的 DataGridView:

POI_grid.AutoGenerateColumns = true;
POI_grid.DataSource = pois; //pois is an object generated from a class

我希望用户编辑此网格中的某些单元格,但需要进行一些验证..

我目前使用文本框验证用户输入,为了简单起见,我被要求在 GridView 中执行此操作。我验证用户输入的方式是这样的: (我验证用户是否只输入了十进制数)

private void txt_X_KeyPress(object sender, KeyPressEventArgs e)
{
    if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != '.' && e.KeyChar != '-'))
    {
        e.Handled = true;
    }

    if (e.KeyChar == '.')
    {
        if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)
            e.Handled = true;
    }

    if (e.KeyChar == '-' && (sender as TextBox).SelectionStart > 0)
    {
        e.Handled = true;
    }
}

验证用户输入的最佳方法是什么,就像我在文本框中但在 DataGridView 中一样?

到目前为止,我已经按照拉米的建议尝试了这个:

 private void POI_grid_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            decimal por_x;
            por_x = Convert.ToDecimal(POI_grid.CurrentCell.Value);

        }

当然,我需要在那里添加一个 try catch 语句以避免出现问题,但只要有可能,我想限制用户在单元格中键入内容,就像我在文本框中所做的那样..

解决方案:

我是这样解决的:

private void POI_grid_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            decimal por_x;
            try
            {
                por_x = Convert.ToDecimal(POI_grid.CurrentCell.Value);
            }
            catch
            {

               POI_grid.CurrentCell.Value= "0";
            }


        }

        private void POI_grid_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            if (e.Exception is FormatException)
            {
                MessageBox.Show("Debe ingresar números decimales solamente", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                MessageBox.Show("Verifique el formato del número ingresado", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

我遇到了这样的问题,但最后我没有找到阻止用户输入非号码承租人的方法,所以我使用 CellEndEdit event 来验证输入 如果它无效,它会显示消息框(只有数字有效)并将单元格重置为 0 。 我希望这对你有用。

我是这样解决的:

private void POI_grid_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            decimal por_x;
            try
            {
                por_x = Convert.ToDecimal(POI_grid.CurrentCell.Value);
            }
            catch
            {

               POI_grid.CurrentCell.Value= "0";
            }


        }

        private void POI_grid_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            if (e.Exception is FormatException)
            {
                MessageBox.Show("Debe ingresar números decimales solamente", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                MessageBox.Show("Verifique el formato del número ingresado", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }