我是 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
最佳答案
试试这个代码
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 事件仅适用于数字带有十进制值的数字的文本框按键事件
关于.net - DataGridView 仅数字单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19855943/