我正在使用DatagridView工具。在这里,我正在对列进行手动输入,并将其直接保存到数据库中。我有5列,其中3列是字母数字,2列是数字列。
我在EditingControlShowing事件中使用处理程序为数字列设置了条件。
If grdLedgerDetails.CurrentCell.ColumnIndex = 4 Then
AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress
ElseIf grdLedgerDetails.CurrentCell.ColumnIndex = 5 Then
AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress
End If
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
此条件正常。但问题是,这个条件适用于所有列。我只是想让它在指定的列上工作。
请帮帮我。
提前致谢。
答案 0 :(得分:1)
这很好用。
Private Sub grdLedgerDetails_EditingControlShowing(sender As Object, e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles grdLedgerDetails.EditingControlShowing
Select grdLedgerDetails.CurrentCell.ColumnIndex
Case 2, 3
RemoveHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress
Case 4, 5
AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress
End Select
End Sub
Private Sub TextBox_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
If Not Char.IsControl(e.KeyChar) And Not Char.IsDigit(e.KeyChar) And e.KeyChar <> "." Then
e.Handled = True
End If
End Sub
答案 1 :(得分:0)
试试这个
Private Sub dgv_EditingControlShowing(ByVal sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs)
RemoveHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress
AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress
End Sub
Private Sub TextBox_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
Select Case grdLedgerDetails.CurrentCell.ColumnIndex
Case 4,5
If Char.IsDigit(CChar(CStr(e.KeyChar))) = False Then e.Handled = True
End Select
End Sub