Подтвердить что ты не робот

Сделать конкретный столбец, только принимать числовое значение в datagridview в событии Keypress

Мне нужно сделать datagridview, который принимает только числовое значение для конкретного столбца только в событии keypress. Есть ли лучший способ сделать это?

4b9b3361

Ответ 1

  • Добавить событие EditingControlShowing
  • В EditingControlShowing убедитесь, что если текущая ячейка находится в нужном столбце.
  • Зарегистрируйте новое событие KeyPress в EditingControlShowing (если указанное выше условие истинно).
  • Удалите любое событие KeyPress, добавленное ранее в EditingControlShowing.
  • В событии KeyPress убедитесь, что если ключ не является цифрой, отмените ввод.

Пример:

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    e.Control.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);
    if (dataGridView1.CurrentCell.ColumnIndex == 0) //Desired Column
    {
        TextBox tb = e.Control as TextBox;
        if (tb != null)
        {
            tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
        }
    }
}

private void Column1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
    {
        e.Handled = true;
    }
}

Ответ 2

Вы должны использовать DataGridView.CellValidating Event следующим образом:

    private void dataGridView1_CellValidating(object sender, 
                                           DataGridViewCellValidatingEventArgs e)
    {
        if (e.ColumnIndex == 1) // 1 should be your column index
        {
            int i;

            if (!int.TryParse(Convert.ToString(e.FormattedValue), out i))
            {
                e.Cancel = true;
                label1.Text ="please enter numeric";
            }
            else
            {
                // the input is numeric 
            }
        }
    }

Ответ 3

 private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        e.Control.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);
        if (dataGridView1.CurrentCell.ColumnIndex == 4) //Desired Column
        {
            TextBox tb = e.Control as TextBox;
            if (tb != null)
            {
                tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
            }
        }

    }
    private void Column1_KeyPress(object sender, KeyPressEventArgs e)
    { 
          // allowed only numeric value  ex.10
        //if (!char.IsControl(e.KeyChar)
        //    && !char.IsDigit(e.KeyChar))
        //{
        //    e.Handled = true;
        //}

               // allowed numeric and one dot  ex. 10.23
        if (!char.IsControl(e.KeyChar)&& !char.IsDigit(e.KeyChar)
             && e.KeyChar != '.')
        {
            e.Handled = true;
        }

        // only allow one decimal point
        if (e.KeyChar == '.'
            && (sender as TextBox).Text.IndexOf('.') > -1)
        {
            e.Handled = true;
        }
    }

Ответ 4

Полученный ответ отлично, если вы не требуете десятичных знаков, как указывали другие. В этом случае вам нужно расширить валидацию, добавить используемые и vars ниже, чтобы получить значение переменной культуры для десятичного разделителя

using System.Globalization;

NumberFormatInfo nfi = Thread.CurrentThread.CurrentCulture.NumberFormat;
char decSeperator;

decSeperator = nfi.CurrencyDecimalSeparator[0];

Расширить проверку до:

if (!char.IsControl(e.KeyChar) && !(char.IsDigit(e.KeyChar) 
| e.KeyChar == decSeperator))
{
    e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == decSeperator
    && (sender as TextBox).Text.IndexOf(decSeperator) > -1)
{
    e.Handled = true;
}

Ответ 5

Private WithEvents txtNumeric As New DataGridViewTextBoxEditingControl

Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing

txtNumeric = CType(e.Control, DataGridViewTextBoxEditingControl)
End Sub

Private Sub txtNumeric_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtNumeric.KeyPress
    If (DataGridView1.CurrentCell.ColumnIndex > 0) Then
        If (Not Char.IsControl(e.KeyChar) And Not Char.IsDigit(e.KeyChar) And Not e.KeyChar = ".") Then
            e.Handled = True
        Else
            'only allow one decimal point
            If (e.KeyChar = "." And txtNumeric.Text.Contains(".")) Then
                e.Handled = True
            End If
        End If
    End If
End Sub

Ответ 6

Вы также можете попробовать этот способ, приняв символ десятичной дроби

    private void Column1_KeyPress(object sender, KeyPressEventArgs e) 
    {
        //allow number, backspace and dot
        if (!(char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == '.'))
        {
            e.Handled = true;

        }
        //allow only one dot
        if (e.KeyChar == '.' && (sender as TextBox).Text.Contains("."))
        {
            e.Handled = true;

        }
    }