【问题标题】:DataGridView Numeric Only Cell?DataGridView 仅数字单元格?
【发布时间】:2013-11-08 09:48:06
【问题描述】:

我是 winforms 的新手。我正在尝试将 DataGridView 的两列设置为仅数字。我不希望用户能够在单元格中输入任何内容,除非它在一列中是自然数和数值在另一个(总是一个小数)。 我认为这很简单..但即使在从 stackoverflow 和其他网站尝试了很多东西之后,我仍然无法实现这一点。

If DataGridView1.CurrentCell.ColumnIndex = 8 Then

    If Not Char.IsControl(e.KeyChar) AndAlso Not Char.IsDigit(e.KeyChar) AndAlso e.KeyChar <> "."c Then
        e.Handled = True
    End If

End If 

【问题讨论】:

  • 如果可行的话,我也会接受 c# 中的任何答案。有可用的在线转换器。 ;)
  • 重复问题[在 Keypress 事件中使特定列仅接受 datagridview 中的数值][1] [1]:stackoverflow.com/questions/12645458/…
  • 使用 EditingControlShowing 而不是 CellValidating 请参阅link

标签: .net vb.net winforms datagridview


【解决方案1】:

试试这个代码

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

        If DataGridView1.CurrentCell.ColumnIndex = 2 Then

            AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress

        ElseIf DataGridView1.CurrentCell.ColumnIndex = 1 Then

            AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress1


        End If

    End Sub

    Private Sub TextBox_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)

        If Char.IsDigit(CChar(CStr(e.KeyChar))) = False Then e.Handled = True

    End Sub

    Private Sub TextBox_keyPress1(ByVal sender As Object, ByVal e As KeyPressEventArgs)

        If Not (Char.IsDigit(CChar(CStr(e.KeyChar))) Or e.KeyChar = ".") Then e.Handled = True

    End Sub

TextBox_keyPress 事件仅用于数字

TextBox_keyPress1 十进制数值事件

【讨论】:

  • 我正在尝试验证 DataGridViewTextBoxCell 我没有使用 TextBox。
  • 是的。你没有使用texbox。但是您可以通过编写文本框事件并在 DataGridView1_EditingControlShowing 事件中添加处理程序来实现您的目标。您无需在表单设计中添加文本框..
  • 我的朋友是迄今为止我遇到的最好的解决方案。很抱歉我花了这么长时间才回复。谢谢。但是,只缺少一件事,那就是.. 如果是十进制数字,则只允许一个小数。
  • @Arbaaz 在编辑后格式化十进制单元格或检查特定单元格是否具有十进制值。我认为格式 (#,0.0) 是最好的解决方案
  • 好吧,我试着检查单元格是否已经有小数,但我总是得到空引用错误......我在一个新问题中问过这个......stackoverflow.com/q/19899456/2064292
【解决方案2】:

如果只关注数据类型验证,那么您可以像这样使用 CellValidating 事件

    private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        //e.FormattedValue  will return current cell value and 
        //e.ColumnIndex & e.RowIndex will rerurn current cell position

        // If you want to validate particular cell data must be numeric then check e.FormattedValue is all numeric 
        // if not then just set  e.Cancel = true and show some message 
        //Like this 

        if (e.ColumnIndex == 1)
        {
            if (!IsNumeric(e.FormattedValue))  // IsNumeric will be your method where you will check for numebrs 
            {
                MessageBox.Show("Enter valid numeric data");
                dataGridView1.CurrentCell.Value = null;
                e.Cancel = true;

            }

        }

    }

【讨论】:

  • 如何清除单元格?如果不是数字,我不希望用户能够输入
  • 修改了我的帖子请查看@Arbaaz
  • 添加了[dataGridView1.CurrentCell.Value = null;]
  • @Arbaaz 至少(SATSON)的其他答案应该有效,您为什么不发表任何评论?您应该对所有答案发表评论,以通知他们改进他们的答案,否则您将没有更好的答案。
  • @KingKing 你是对的..我很抱歉..我现在已经在那里发表评论了。
【解决方案3】:
If e.ColumnIndex = 6 Then
    If Not IsNumeric(e.FormattedValue) Then
        ' IsNumeric will be your method where you will check for numebrs 
        MessageBox.Show("Enter valid numeric data")
        DataGridView1.CurrentCell.Value = Nothing

        e.Cancel = True

    End If
End If

【讨论】:

    【解决方案4】:

    以下代码是 Satish 解决方案的扩展。它将有助于控制 DataGridView 单元格的值。文本框函数仅用于将单元格附加到文本框事件。无需在 DataGridView 或表单的任何位置添加文本框。

    Private Sub DataGridView_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView.EditingControlShowing
        If DataGridView.CurrentCell.ColumnIndex = 2 Then 'Numeric column with decimal point
            AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress
    
        ElseIf DataGridView.CurrentCell.ColumnIndex = 3 Then 'Numeric column without Decimal
            AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress1
    
        ElseIf DataGridView.CurrentCell.ColumnIndex = 4 Then 'Selected Values only
            AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress2
    
        ElseIf DataGridView.CurrentCell.ColumnIndex = 5 Then 'Email Column
            AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress3
    
        End If
    
    End Sub
    
    Private Sub TextBox_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
        'Allows Numeric values, one decimal point and BackSpace key
        Dim numbers As Windows.Forms.TextBox = sender
        If InStr("1234567890.", e.KeyChar) = 0 And Asc(e.KeyChar) <> 8 Or (e.KeyChar = "." And InStr(numbers.Text, ".") > 0) Then
            e.KeyChar = Chr(0)
            e.Handled = True
        End If
    End Sub
    
    Private Sub TextBox_keyPress1(ByVal sender As Object, ByVal e As KeyPressEventArgs)
        'Allow Numeric values, BackSpace key. Disallows decimal point (i.e. dot) 
        Dim numbers As Windows.Forms.TextBox = sender
        If InStr("1234567890", e.KeyChar) = 0 And Asc(e.KeyChar) <> 8 Then
            e.KeyChar = Chr(0)
            e.Handled = True
        End If
    End Sub
    
    
    Private Sub TextBox_keyPress2(ByVal sender As Object, ByVal e As KeyPressEventArgs)
        'Allow selected values only
        If InStr("1234567890!@#$%^&*()_+=-", e.KeyChar) > 0 Then
            e.KeyChar = Chr(0)
            e.Handled = True
        End If
    End Sub
    
    Private Sub TextBox_keyPress3(ByVal sender As Object, ByVal e As KeyPressEventArgs)
        'Martch function, Needs to add "Imports System.Text.RegularExpressions" at the top of Class
        'Allows Email values
        Dim Email As Windows.Forms.TextBox = sender
        If Email.Text <> "" Then
            Dim rex As Match = Regex.Match(Trim(Email.Text), "^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,3})$", RegexOptions.IgnoreCase)
            If rex.Success = False Then
                MessageBox.Show("Please Enter a valid Email Address", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Email.BackColor = Color.Red
                Email.Focus()
                Exit Sub
            Else
                Email.BackColor = Color.White
            End If
        End If
    End Sub
    

    【讨论】:

      【解决方案5】:

      试试这个代码。它与投票最多的答案几乎相同,但我编辑了KeypressEvent 代码以使其变得简单,即使您必须输入十进制数字,您也可以使用它。享受。 :)

      Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
      
          If DataGridView1.CurrentCell.ColumnIndex = 2 Then
      
              AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress
      
          End If
      
      End Sub
      
      Private Sub TextBox_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
      
           If (Not Char.IsControl(e.KeyChar) _
                      AndAlso (Not Char.IsDigit(e.KeyChar) _
                      AndAlso (e.KeyChar <> Microsoft.VisualBasic.ChrW(46)))) Then
              e.Handled = True
          End If
      
      End Sub
      

      【讨论】:

        【解决方案6】:
        Private Sub DGV_EditingControlShowing(sender As Object, e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DGV_TimeSheetMain.EditingControlShowing
            '       '*************Allow only Numbers in DataGridView*************
            Dim txtEdit As TextBox = e.Control
            'remove any existing handler
            RemoveHandler txtEdit.KeyPress, AddressOf TextEdit_Keypress
            AddHandler txtEdit.KeyPress, AddressOf TextEdit_Keypress
        End Sub
        
        Private Sub TextEdit_Keypress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
            'Test for numeric value or backspace in first column
            If DGV.CurrentCell.ColumnIndex = 1 Then
                If IsNumeric(e.KeyChar.ToString()) Or e.KeyChar = ChrW(Keys.Back) Then
                    e.Handled = False 'if numeric display
                Else
                    e.Handled = True  'if non numeric don't display
                End If
            End If
        End Sub
        

        【讨论】:

        • 此代码也允许退格,而且效果很好!
        【解决方案7】:

        用 lambda 试试这个

        Private Sub dgv_pararelhp_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles dgv_pararelhp.EditingControlShowing
            If dgv_pararelhp.CurrentCell.ColumnIndex = 0 Then'// change this optional your index column.
                 AddHandler CType(e.Control, TextBox).KeyPress, Sub(s_, e_)
                                                                    If Char.IsDigit(CChar(CStr(e_.KeyChar))) = False Then e_.Handled = True
                                                                 End Sub
               End If
        End Sub
        

        【讨论】:

          【解决方案8】:
          Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As         System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
                  AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress
           End Sub
           Private Sub TextBox_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
                  If Char.IsDigit(CChar(CStr(e.KeyChar))) = False Then e.Handled = True
                  If Not (Char.IsDigit(CChar(CStr(e.KeyChar))) Or e.KeyChar = ".") Then e.Handled = True
                  If e.KeyChar = " "c Then e.Handled = False
            End Sub
          

          【讨论】:

          • 还请提供一些解释,不要只是粘贴一大块代码。
          猜你喜欢
          • 1970-01-01
          • 2013-01-13
          • 2020-12-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-10-30
          相关资源
          最近更新 更多