KeyPress handler being applied to wrong control - vb.net

I have a .KeyPress event handler which is supposed to limit/control the keys which can be entered in a specific TextBox (more precisely, any of the textboxes in a specific DataGridViewTextBoxColumn)
Private Sub dgv_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles dgv.EditingControlShowing
If dgv.CurrentCell.ColumnIndex = myColumn.Index And Not e.Control Is Nothing Then
DirectCast(e.Control, TextBox).CharacterCasing = CharacterCasing.Upper
DirectCast(e.Control, TextBox).MaxLength = 10
AddHandler DirectCast(e.Control, TextBox).KeyPress, AddressOf controlKeyPress
End If
End Sub
Private Sub controlKeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
Dim charEnum As Integer = CUInt(Microsoft.VisualBasic.Asc(e.KeyChar))
Dim tb As TextBox = DirectCast(sender, TextBox)
Select Case charEnum
Case 8
' Always permit the keying of backspace (no suppression)
Case 42
' Permit the keying of asterisk (42) but only if it is the first character (otherwise, suppress the key press)
If Not tb.SelectionStart = 0 Then e.KeyChar = ""
Case 46
' Permit the keying of period (46) but only if it is not the first character and the first character is not an asterisk (otherwise, suppress the key press)
If tb.SelectionStart = 0 OrElse tb.Text.FirstOrDefault = "*" Then e.KeyChar = ""
Case 65 To 90, 97 To 122
' Permit the keying of upper-case alpha (65-90) and lower-case alpha (97-122) as long as the first character is not an asterisk (otherwise, suppress the key press)
If tb.Text.FirstOrDefault = "*" Then e.KeyChar = ""
Case Else
' All other characters, suppress the key press (set the KeyChar to nothing)
e.KeyChar = ""
End Select
End Sub
What's weird is, the same handler seems to be getting applied to other TextBox controls in the DataGridView, but in a different column (i.e. not in myColumn) Which is strange because I have a specific condition in the EditingControlShowing event that specifies that the handler should only be applied if the .ColumnIndex of the control matches that of the column to which it should apply (i.e. If dgv.CurrentCell.ColumnIndex = myColumn.Index) So I'm not sure why the same handler is being applied to a TextBox that's not in myColumn?
Also, it doesn't appear to be consistent - when I initially load the DGV, the other textboxes have no restrictions on them (as expected); when I go to edit a row, and the handler is applied to myColumn (as expected), the same handler also seems to be applied immediately to any other textboxes in the same row (but in debugging, I can't seem to trap where this happens, I can only trap the application of the event handler to the correct control)
I'm not sure if I should have a RemoveHandler call somewhere - and if so, where, because I can't find the point at which the handler is being applied erroneously in the first place?
I tried this but it doesn't seem to have any effect (again, while debugging, when I click in a TextBox in myOtherColumn, it does hit that line, but the restriction is still imposed anyway?)
Private Sub dgv_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles dgv.EditingControlShowing
If dgv.CurrentCell.ColumnIndex = myColumn.Index Then
DirectCast(e.Control, TextBox).CharacterCasing = CharacterCasing.Upper
DirectCast(e.Control, TextBox).MaxLength = 10
AddHandler DirectCast(e.Control, TextBox).KeyPress, AddressOf controlKeyPress
ElseIf dgv.CurrentCell.ColumnIndex = myOtherColumn.Index Then
RemoveHandler DirectCast(e.Control, TextBox).KeyPress, AddressOf controlKeyPress
End If
End Sub
All suggestions welcome!

The DataGridView control will reuse an editing control if it can to improve performance. You should keep a reference to the editing control from the EditingControlShowing event handler and use a RemoveHandler statement in the CellEndEdit event handler.
Actually, you may not need to keep the reference. You may be able to use the EditingControl property of the grid. Try that first.
EDIT:
I have just tested for myself and the EditingControl property of the grid is Nothing when the CellEndEdit event is raised, so my second suggestion above is out. That means that you need to retain a reference to the editing control from the EditingControlShowing event handler. If you're going to do that though, you may as well not use AddHandler and RemoveHandler. It's simpler to declare the field WithEvents and then use a Handles clause on the event handler, e.g.
Private WithEvents editingControl As TextBox
Private Sub DataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
If DataGridView1.CurrentCell.ColumnIndex = 0 Then
editingControl = DirectCast(e.Control, TextBox)
End If
End Sub
Private Sub DataGridView1_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
editingControl = Nothing
End Sub
Private Sub EditingControl_KeyPress(sender As Object, e As KeyPressEventArgs) Handles editingControl.KeyPress
Console.WriteLine(e.KeyChar)
End Sub
That code will assign the editing control to the field if and only if the cell being edited is in the first column. Any control assigned to that field will have its events handled and the field is always reset when an editing session ends.

Related

how to create button shortcuts in vbnet

I tried creating keyboard shortcuts for my buttons.
Here is my code
Private Sub form_main_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
If Keys.ControlKey + Keys.N Then
'btn_add.PerformClick()
addentry()
ElseIf Keys.ControlKey + Keys.E Then
'btn_edit.PerformClick()
editentry()
End If
End Sub
The problem is even when I press other buttons the function is still called. I also tried using form keydown property but the result is still the same.
additional info:
the functions addentry and editentry will just call the form_addedit
btn_add will call for addentry
btn_edit will call for editentry
First of all Keys.*** is just an enumeration. Every entry in it is just a number representing a key code. So you are currently just adding numbers together.
Keys.ControlKey is 17 and Keys.N is 78, so you're literally writing:
If 17 + 78 Then
Which will always return True because it's greater than 0.
To do what you ask you must check which key was pressed by checking the event arguments (EventArgs) passed to the event.
But since you are using the KeyPress event you cannot get the key enumeration out of the event args, so I recommend you to use the KeyDown event instead.
Private Sub form_main_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
If e.Control = True AndAlso e.KeyCode = Keys.N Then
addentry()
ElseIf e.Control = True AndAlso e.KeyCode = Keys.E Then
editentry()
End If
End Sub
If you put an ampersand in the .Text property of the button, Alt+key will fire the button, for example B&utton1 will fire with Alt+u.

VB.NET 2010 DataGridView Handling Keypress via EditingControlShowing Event

I am working with a DataGridView for the first time and while I have MANY questions, this latest issue is vexing me.
Summary of issue:
I have a DataGridView (dgv) which I have a set of columns defined. Some readonly some editable.
For the editable columns I need four things to occur.
1) Allow Numeric entry
2) Allow maximum of 2 digits
3) Zero Pad any entries <2 digits
4) My ISSUE:
If the user types in a two digit number, I want to detect that and TAB to the next column. I cannot get this to work.
Sample code (with some known working items left out):
Private Sub dgvDiary_EditingControlShowing(sender As Object, e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles dgvDiary.EditingControlShowing
Dim txtEdit As TextBox = e.Control
txtEdit.MaxLength = 2
'remove any existing handler
RemoveHandler txtEdit.KeyPress, AddressOf txtdgvDiaryEdit_Keypress
AddHandler txtEdit.KeyPress, AddressOf txtdgvDiaryEdit_Keypress
End Sub
Private Sub txtdgvDiaryEdit_Keypress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
'Test for numeric value or backspace
If IsNumeric(e.KeyChar.ToString()) _
Or e.KeyChar = ChrW(Keys.Back) Then
e.Handled = False 'if numeric
Else
e.Handled = True 'if non numeric
End If
'If user typed in 2 characters, move on!
'Don't work!
If Strings.Len(Me.dgvDiary.Rows(Me.dgvDiary.CurrentRow.Index).Cells(Me.dgvDiary.CurrentCell.ColumnIndex).Value) = 2 Then
SendKeys.Send("{TAB}")
End If
End Sub
Basically during this event I'm not able to see what the value of the cell "will be" when entered.
I tried adding a ".RefreshEdit" and a ".Commit" but they didn't work.
Any way to test the code within this event OR is there an event that would fire IMMEDIATELY afterward that I can use?
You are looking in the wrong place. You need to examine the text in the TextBox, not the grid, to see how many characters are currently being typed. Try using the TextChanged event for that:
Private Sub txtdgvDiaryEdit_TextChanged(sender As Object, e As EventArgs)
If DirectCast(sender, TextBox).Text.Length = 2 Then
SendKeys.Send("{TAB}")
End If
End Sub
Like your other code, add the handlers:
'remove any existing handler
RemoveHandler txtEdit.TextChanged, AddressOf txtdgvDiaryEdit_TextChanged
AddHandler txtEdit.TextChanged, AddressOf txtdgvDiaryEdit_TextChanged
RemoveHandler txtEdit.KeyPress, AddressOf txtdgvDiaryEdit_KeyPress
AddHandler txtEdit.KeyPress, AddressOf txtdgvDiaryEdit_KeyPress
Alternatively, you can check to see if the TextBox only has one character, and if the KeyPress is passing in another number, send your Tab key then. You would remove the TextChanged event code in this case:
Private Sub txtdgvDiaryEdit_KeyPress(sender As Object, e As KeyPressEventArgs)
'Test for numeric value or backspace
If IsNumeric(e.KeyChar.ToString()) _
Or e.KeyChar = ChrW(Keys.Back) Then
e.Handled = False 'if numeric
Else
e.Handled = True 'if non numeric
End If
If DirectCast(sender, TextBox).Text.Length = 1 AndAlso Char.IsNumber(e.KeyChar) Then
SendKeys.Send("{TAB}")
End If
End Sub

How to set the value of a DataGridView's EditingControl

I need to set the text value of a DataGridView.EditingControl. I've tried
myDGV.EditingControl.Text() = "1/1/2001"
and
myDGV.EditingControl.Text = "1/1/2001"
and
myDGV.EditingControl.Text("1/1/2001")
which causes an InvalidCastException (didn't check that could only be an integer).
There is no Value() property for the control, so how do I set the the value?
(Yes, I've verified that the cell is in edit mode)
You need to handle the EditingControlShowing event.
Private Sub HandleDgvEditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles Dgv.EditingControlShowing
If (TypeOf e.Control Is DataGridViewTextBoxEditingControl) Then
With DirectCast(e.Control, DataGridViewTextBoxEditingControl)
.Text = "1/1/2001"
End With
End If
End Sub
Note that this event will be fired for all editable cells. If you only want to manipulate the edit control for a given column you need to add another condition. Something like this:
If (Me.Dgv.CurrentCell.OwningColumn is Me.DgvFooColumn) Then
If you need to revert the edit from the CellValidating event then store the original value when the edit control is shown.
Private Sub HandleDgvEditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles Dgv.EditingControlShowing
'Cache the edit control text
Me.cachedEditText = e.Control.Text
End Sub
Private Sub HandleDgvCellValidating(sender As Object, e As DataGridViewCellValidatingEventArgs) Handles Dgv.CellValidating
'Ensure that the edit control exists
If (Not Me.Dgv.EditingControl Is Nothing) Then
'Validate the edit
If (Not valid) Then
Me.Dgv.EditingControl.Text = Me.cachedEditText
End If
End If
End Sub
Private cachedEditText As String

How to prevent special characters in datagridview using vb.net

I have a windows forms vb.net program that uses a datagridview. I'm trying to find a way to prevent a user from entering special characters (e.g. $,#,!,#,%,^,&) in my datagridview. When the user inputs a special character I have an approprioate message box appear explaining their mistake, then I provide them a default value. I have everything working except a way to prevent the special character or symbols. I'm thinking something like this has to work, but I can't seem to find any way of preventing this sort of entry:
If (columnindex = 0) Then 'checking value for column 1 only
Dim cellString = DataGridView1.Rows(rowindex).Cells(columnindex).value
If cellString String.IsSymbol(cellString) = true Then
MessageBox.Show("Special Characters Not Allowed")
End If
DataGridView1.Rows(rowindex).Cells(columnindex).value = "Default Value"
Exit Sub
End If
You can use the EditingControlShowing event to register a KeyPress function for the input box.
Private Sub YourDataGridView_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles YourDataGridView.EditingControlShowing
Try
RemoveHandler e.Control.KeyPress, AddressOf YourFunctionToPreventSpecialCharacters
Catch ex As Exception
End Try
If Me.dgvTableViewer.CurrentCell.ColumnIndex = YourDataGridView.Columns("YourColumn").Index Then
AddHandler e.Control.KeyPress, AddressOf YourFunctionToPreventSpecialCharacters
End If
End Sub
Try and Put this in the DataGridView's keydown event:
Private Sub DataGridView1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles DataGridView1.KeyDown
Select Case e.KeyCode
Case Keys.D0 To Keys.D9 And e.Shift
MsgBox("NOPE.")
e.SuppressKeyPress = True
End Select
End Sub
That basically checks if the keypress is coming from the 0-9 keys on your computer and also if you are holding the SHIFT Key. If it is then it displays a Msgbox and Suppresses the keypress. This blocks chars on your keyboard's 0-9 shift !##$%^&*(). You can edit this like
Case Keys.A
e.Suppress ...
Msgbox ... etc

EditingControlShowing events firing multiple times

I have a DGV in VB.Net 2008 connected to an Access DB table. The DGV is not Read Only, but is full of read-only columns except for one, which contains a combo box. The combo box allows the user to select an outcome for that particular row, and then the program copies in a pre calculated value into the "Profit" column depending upon the item selected in the combobox. Then the user hits the Save button and the DB updates (currently via SQL methods in the XSD).
Easy enough so far.
Here is the code.
Private Sub DGUserBets_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DGUserBets.EditingControlShowing
Dim combo As ComboBox = CType(e.Control, ComboBox)
If (combo IsNot Nothing) Then
// Remove an existing event-handler, if present, to avoid
// adding multiple handlers when the editing control is reused.
RemoveHandler combo.SelectedIndexChanged, _
New EventHandler(AddressOf DGUBStake_SelectedIndexChanged)
// Add the event handler.
AddHandler combo.SelectedIndexChanged, _
New EventHandler(AddressOf DGUBStake_SelectedIndexChanged)
End If
End Sub
Private Sub DGUBStake_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim myStatus As ComboBox = CType(sender, ComboBox)
Dim row = DGUserBets.CurrentRow
Select Case myStatus.SelectedIndex
Case 0
row.Cells("DGUBProfit").Value = 0
// pending. no action
Case 1
row.Cells("DGUBProfit").Value = row.Cells("DGUBIfWin").Value
// win
Case 2
// loses
row.Cells("DGUBProfit").Value = row.Cells("DGUBIfLose").Value
Case 3
// void
row.Cells("DGUBProfit").Value = 0
End Select
End Sub
The problem I have is that it would seem that if a user selects the desired outcome from the combobox but does NOT hit Enter, and simply mouses on to a different combobox to again select the outcome for a different row, the first eventhandler is not disconnected and thus the events fire multiple times. This then causes various default MsgBox errors and brings up problems when the user tries to commit all changes to the DB/exit program etc etc.
What do I need to do? Do I need to .EndEdit somewhere appropriate to force the row to save the changes? And where should I call this?
Thank you.
A quick glance at the code brings up this question:
If you create a new EventHandler when removing the existing one is it the same one?
I have had a similar issue, add a handler for CellLeave if the cell being exited is the cell you are looking for (IE e.ColumnIndex = myEditableColumn.Index) then call gv.EndEdit()
Also I would recommend making the handlers member variables for assignment and removal because it seems nicer then always saying Remove New and Add New.
CKRet/Quintin , thank you for the fast responses.
A quick try with this code seems better and breakpointing and stepping through the code seems to be firing the events correctly. I'm fairly new to .NET as the last real VB programming I did was VB6 so I'm not sure if this is the most elegant way to solve the problem.
Also a note that when LastEventHandler = Nothing, calling the RemoveHandler does not throw an exception, which is quite nice.
Maybe I should suggest to MS they should update that article.
Private Sub DGUserBets_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DGUserBets.EditingControlShowing
Dim combo As ComboBox = CType(e.Control, ComboBox)
Static LastEventHandler As EventHandler
If (combo IsNot Nothing) Then
// Remove an existing event-handler, if present, to avoid
// adding multiple handlers when the editing control is reused.
RemoveHandler combo.SelectedIndexChanged, _
LastEventHandler
LastEventHandler = New EventHandler(AddressOf DGUBStake_SelectedIndexChanged)
// Add the event handler.
AddHandler combo.SelectedIndexChanged, _
LastEventHandler
End If
End Sub
Simpler code which also appears to work well, as suggested by CKRet:
Dim combo As ComboBox = CType(e.Control, ComboBox)
If (combo IsNot Nothing) Then
RemoveHandler combo.SelectedIndexChanged, AddressOf DGUBStake_SelectedIndexChanged
AddHandler combo.SelectedIndexChanged, AddressOf DGUBStake_SelectedIndexChanged
End If
I know this is an archaic post, but after buggering around with this same problem for half a day I've found a way to solve this another way, so I thought it would be worth sharing.
Adding a second handler to handle the leave event of the combobox which then removes the handler of selectedvalue changed. Appears to work quite slick, and unlike another option i found gives the desired resulting action (unlike removing the value changed handler on the actual handling event which then won't fire if you re-select from the same combobox)
Private LastEventHandler As EventHandler = AddressOf Me.ComboBoxValueChanged
Private Sub dgvThisDatagrid_EditingControlShowing(sender As Object, e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles dgvOutstandingReminders.EditingControlShowing
If TypeOf (e.Control) Is ComboBox Then
Dim cboThisComboBox = DirectCast(e.Control, ComboBox)
AddHandler cboThisComboBox.SelectedValueChanged, LastEventHandler
AddHandler cboThisComboBox.Leave, AddressOf RemoveValueChangedHandler
End If
End Sub
Private Sub ComboBoxValueChanged(ByVal sender As Object, ByVal e As System.EventArgs)
If TypeOf (sender) Is ComboBox Then
Dim cboThisComboBox = DirectCast(sender, ComboBox)
MessageBox.Show("Value = " & cboThisComboBox.SelectedValue.ToString() & Environment.NewLine & "Text = " & cboThisComboBox.Text) ' Display index
End If
End Sub
Private Sub RemoveValueChangedHandler(ByVal sender As Object, ByVal e As System.EventArgs)
If TypeOf (sender) Is ComboBox Then
Dim cboThisCombobox = DirectCast(sender, ComboBox)
RemoveHandler cboThisCombobox.SelectedValueChanged, LastEventHandler
End If
End Sub