Datagridview只允许输入数字
第一步:给TextBox注册事件
Private Sub DataGridView1_EditingControlShowing(sender As Object, e As winForms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing If e.Control.GetType Is GetType(winForms.DataGridViewTextBoxEditingControl) Then Dim txtEdit As winForms.TextBox = e.Control 'remove any existing handler RemoveHandler txtEdit.KeyPress, AddressOf txtEdit_Keypress AddHandler txtEdit.KeyPress, AddressOf txtEdit_Keypress End If End Sub
第二步:设置允许的按键
Private Sub txtEdit_Keypress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) If DataGridView1.CurrentCell.ColumnIndex = 0 Then Dim txtbox As winForms.TextBox = CType(sender, winForms.TextBox) '光标位置 Dim n As Int16 = txtbox.SelectionStart '文本框内的字符串’ Dim t As String = CType(sender, winForms.TextBox).Text '----------------------------------------------------------------' '如果光标在起始位置并且已经有负号时,什么都不能输入 '如果光标在起始位置并且没有负号时,允许输入负号’ '如果没有小数点,允许输入小数点’ '允许输入数字或退格键’ '----------------------------------------------------------------' If n = 0 AndAlso t.IndexOf("-") > -1 Then e.Handled = True ElseIf n = 0 AndAlso t.IndexOf("-") < 0 AndAlso e.KeyChar = "-" Then e.Handled = False ElseIf t.IndexOf(".") < 0 AndAlso e.KeyChar = "." Then e.Handled = False ElseIf IsNumeric(e.KeyChar.ToString()) OrElse e.KeyChar = ChrW(winForms.Keys.Back) Then e.Handled = False Else e.Handled = True End If End If End Sub