VB.NET 2010 DataGridView Handling Keypress via EditingControlShowing Event - vb.net

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

Related

KeyPress handler being applied to wrong control

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.

Unselect a listbox item if it contains a specific character (don't allow its selection)

I have a listbox1 with a list of items. If a user has to select an item with a single mouse click and if that selected list item has an equal sign in it, it must immediately display a message stating this and deselect the item.
I have looked at various solutions all of which does not work as I want it to:-
Below is my code which works ummmm most of the time but not when two or more items have already been previously selected. I need a always will work solution.
Private Sub ListBox1_MouseClick(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseClick
For I = 0 To ListBox1.SelectedItems.Count - 1
If Not ListBox1.Items(I).ToString.Contains("=") Then
ListBox1.SetSelected(I, False)
' MsgBox("Please only select items that have = in description ! ! ! Edit item if you want to include . . .", MsgBoxStyle.Critical)
End If
Next
ListBox1.Refresh()
End Sub
I think it's better using SelectedIndexChangedEvent:
Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
With CType(sender, ListBox)
For i As Integer = .SelectedItems.Count - 1 To 0 Step -1
If Not IsNothing(.SelectedItems(i)) AndAlso Not .SelectedItems(i).ToString.Contains("=") Then
MsgBox("Invalid selection.")
.SelectedItems.Remove(.SelectedItems(i))
End If
Next i
End With
End Sub
One solution for this problem is to get - in the SelectedIndexChanged event - the indices of the invalid selections if any to deselect them and show the message. Handling the SelectedIndexChanged event in particular is to make it work with the mouse and keyboard inputs.
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) _
Handles ListBox1.SelectedIndexChanged
With ListBox1
Dim invalidSel = .SelectedIndices.Cast(Of Integer).
Where(Function(i) Not .GetItemText(.Items(i)).Contains("="))
If invalidSel.Any() Then
RemoveHandler ListBox1.SelectedIndexChanged,
AddressOf ListBox1_SelectedIndexChanged
For Each i In invalidSel
.SetSelected(i, False)
Next
MessageBox.Show("Please....")
AddHandler ListBox1.SelectedIndexChanged,
AddressOf ListBox1_SelectedIndexChanged
End If
End With
End Sub
Note, removing then adding the handler again is to avoid showing the message box repeatedly in the multi-selection modes. Without it, the event fires for each .SetSelected(i, False) call.

How to validate textbox array elements created through loop using VB.net?

I have created 288 textboxes through array and loop in VB.net. Is there any possible way on validating each textbox on KeyPress event to determine if the input is an integer? Thanks so much for your help!
You can do this by adding event handler in the array function.
Dim txt As TextBox
AddHandler txt.KeyPress, AddressOf KeyPressToCheckInput
then write the KeyPress Function
Sub KeyPressToCheckInput(sender As Object, e As KeyPressEventArgs)
If e.KeyChar <> ChrW(Keys.Back) Then 'checks for backspace
If Char.IsNumber(e.KeyChar) Then
'anything you want to do about it'
Else
e.Handled = True 'ignores if the character is not a number
End If
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