本文介绍了DataGridView 仅数字单元格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 winforms 的新手..我试图将 DataGridView 的两列设置为仅数字.. 我不希望用户能够在单元格中键入任何内容,除非它是一列中的自然数和数值在另一个(总是一个小数).我认为这很简单..但即使在从 stackoverflow 和其他网站尝试了很多东西之后,我仍然无法实现这一点.
I am new to winforms..I am trying to set two column of DataGridView to Numeric Only.. I do not want user to be able to type anything into a cell unless its a natural number in one column and a numeric value in another(which always one decimal).I thought this would be simple.. but even after trying a lot of things from stackoverflow and other sites i am still unable to achieve this.
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
推荐答案
试试这个代码
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_keyPress Event for only numeric
TextBox_keyPress1 带有十进制值的数字事件
TextBox_keyPress1 Event for numeric with decimal value
这篇关于DataGridView 仅数字单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!