C# 在 Keypress 事件中使特定列只接受 datagridview 中的数值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12645458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:59:50  来源:igfitidea点击:

Make a specific column only accept numeric value in datagridview in Keypress event

c#datagridviewkeypress

提问by Eplzong

I need to make datagridview that only accept the numeric value for specific column only in keypress event. Is there any best way to do this?

我需要制作仅在按键事件中仅接受特定列的数值的数据网格视图。有没有最好的方法来做到这一点?

采纳答案by Muhammad Mobeen Qureshi

  • Add an event of EditingControlShowing
  • In EditingControlShowing, check that if the current cell lies in the desired column.
  • Register a new event of KeyPress in EditingControlShowing(if above condition is true).
  • Remove any KeyPress event added previously in EditingControlShowing.
  • In KeyPress event, check that if key is not digit then cancel the input.
  • 添加 EditingControlShowing 事件
  • 在 EditingControlShowing 中,检查当前单元格是否位于所需的列中。
  • 在 EditingControlShowing 中注册一个新的 KeyPress 事件(如果上述条件为真)。
  • 删除之前在 EditingControlShowing 中添加的任何 KeyPress 事件。
  • 在 KeyPress 事件中,检查如果 key 不是数字,则取消输入。

Example:

例子:

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;
    }
}

回答by hamed

You must use DataGridView.CellValidating Eventlike this :

您必须像这样使用DataGridView.CellValidating 事件

    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 
            }
        }
    }

回答by saurabh agrawal

 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;
        }
    }

回答by D Kavitha Vijay

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

回答by Rupert

The answer given is excellent unless you require decimal places as others have pointed out. In this event you need to extend the validation, add the using and vars below to get a culture variable value for the decimal separator

除非您像其他人指出的那样需要小数位,否则给出的答案非常好。在这种情况下,您需要扩展验证,添加下面的 using 和 vars 以获取小数点分隔符的区域性变量值

using System.Globalization;

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

decSeperator = nfi.CurrencyDecimalSeparator[0];

Extend the validation to:

将验证扩展到:

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;
}

回答by Ramgy Borja

You could also try this way, with accept decimals character

您也可以尝试这种方式,接受小数字符

    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;

        }
    }