One column in a vb.net Datagridview should not allow paste of non-integers - vb.net

I have a datagridview and one of the columns is a Quantity column that should only allow integers. No negative symbols or decimal points. I have prevented the user from typing in any characters but they can paste them in. I could stop this in validation but I would ideally like to not even show characters that are pasted in. How would I detect and remove pasted in letters and in what event?
Ideally I would also like for only the paste to not work, so if the field already had a 2 in it and they pasted "test" then the 2 would remain, although that isn't as important.

Here's one approach:
'Set a flag to show when the form has finished initialising
Dim initialising As Boolean = True
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Form is initialised so set boolean to false
initialising = False
End Sub
Private Sub DataGridView1_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
'Only process once the form is initialised as values don't exist yet!
If Not initialising Then
If Not IsNothing(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value) Then
'If the clipboard contains text
If Clipboard.ContainsText Then
' Check to see if the value of the cell matches whats in the clipboard
If CStr(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value) = Clipboard.GetText Then
'You know its been pasted
If Not IsNumeric(CStr(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value)) Then
'This value should be rejected
Else
'This value is allowed
End If
End If
End If
End If
End If
End Sub
See my commentated code for an explanation.
I'm not sure you will want to do it on this event as it doesn't fire the event until the user leaves the cell. Hopefully however my approach of checking the value against what is in the clipboard might help you to identify if its a pasted value.

You'd have to implement a validating method and call it in some of the DataGridView's events (I'm thinking KeyDown/Keypress and MouseClick).
I think it's bad practice, because you'll be struggling to find more ways in which the user can trick your application; most apps nowadays let the user input whatever they want, but keep the user from completing her task until she has sanitized her input. Most also give clear on-screen instructions on how to do so.

Something like this
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
End Sub

Related

How do I get the textbox to enable after a certain amount of text is inputted?

So my next question(i know i know ive had a lot of questions already but im learning and my teachers suck)
but I am trying to get the textbox to go to readonly after a certain amount of text has been entered. I know how to make it a read only textbox but only after Ive had one set of data entered. i need it to be readonly after 7 days of data has been entered
I've tried inputtextbox.enabled = false
'Validating if user input is a number or not
Dim output As Integer
If Not Integer.TryParse(InputTextbox.Text, output) Then
MessageBox.Show("ERROR! Data must be a number")
InputTextbox.Text = String.Empty
Else
UnitsTextbox.AppendText(Environment.NewLine & InputTextbox.Text)
InputTextbox.Text = String.Empty
End If
InputTextbox.Enabled = False
I'm expecting it to disable after the user has entered 7 days worth of data but it only disables after one day of data is entered
Since the entries to UnitsTextbox are all done in code, this TextBox can be set to read only at design time.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim output As Integer
If Not Integer.TryParse(InputTextbox.Text, output) Then
MessageBox.Show("ERROR! Data must be a number")
Else
UnitsTextbox.AppendText(Environment.NewLine & InputTextbox.Text)
End If
'Moved this line outside of the If because it happens either way
InputTextbox.Text = String.Empty
If UnitsTextbox.Lines.Length >= 7 Then
Button2.Enabled = False
End If
End Sub
Here's some simple psuedocode
Private Sub InvalidateTextbox(sender As TextBox, e As KeyEventArgs) Handles TextBox1.KeyUp, TextBox2.KeyUp
'FOR ANY TEXTBOX YOU WANT TO CONTROL WITH THIS SUB, ADD AN ADDITIONAL HANDLE.
If Strings.Len(sender.Text) > 7 Then
'^SIMPLE CONDITIONAL, CHECKING IF THE LENGTH IS MORE THAN SEVEN CHARACTERS, MODIFY THIS TO SUIT YOUR NEEDS.
sender.Enabled = False
'^IF THE CONDITIONAL IS TRUE, DEACTIVATE THE CONTROL, IF THAT IS WHAT YOU ARE LOOKING FOR.
sender.ReadOnly = true
'^IF YOU WANT READONLY,NOT ENABLED/DISABLED.
End If
End Sub
This code will execute every time a key is pressed while the text boxes are active. What is after "Handles" defines what events will trigger the sub.
sender becomes the textbox object that triggered the sub. e holds all the event arguments for the keyboard, so you can evaluate things like which key was pressed and other neat things.
There was some confusion on if you wanted enabled/disabled or readonly, both options included.

How to create something similar to google style currency converter with VB.NET

Ok I have a bit of a weird question here. I have a program similar to a currency converter (it performs a mathematical function in order to produce a value to go in another textbox). What I want it to be able to do is identify the last textbox that you edited (there are 4) and then update the rest based on what you have inputted, the user then must be able to change a different textbox to change all of them.
If anyone can get me started on how to do it or even some sample code that would be much appreciated, thanks!
Sorry if I'm not making sense, just have a look at the google currency converter and think that with two more editable boxes.
This might be what you want if I understand you correctly.
In the form class, you have a variable called lastTextBoxChangedName which keeps track of which text box was the last to be edited.
Next there is an event handler which will fire when any of the four TextBoxes are changed. This merely updates lastTextBoxChangedName.
When you have finihed editing a textbox, and tab to the next one or click on something that causes a TextBox to lose input focus, the next event handler executes. This looks at lastTextBoxChangedName to see which was the last edited TextBox and you can insert your update code to replace the comments in the Select Case block.
Public Class Form1
Dim lastTextBoxChangedName As String
Private Sub TextBox_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged, TextBox2.TextChanged, TextBox3.TextChanged, TextBox4.TextChanged
lastTextBoxChangedName = sender.name
End Sub
Private Sub TextBox1_LostFocus(sender As Object, e As EventArgs) Handles TextBox1.LostFocus, TextBox2.LostFocus, TextBox3.LostFocus, TextBox4.LostFocus
updateTextBoxes()
End Sub
Private Sub updateTextBoxes()
Select Case lastTextBoxChangedName
Case "TextBox1"
'do updates appropriate to textbox1 changed
Case "TextBox2"
'do updates appropriate to textbox2 changed
Case "TextBox3"
'do updates appropriate to textbox3 changed
Case "TextBox4"
'do updates appropriate to textbox4 changed
End Select
End Sub
End Class
However, if you already have separate event handlers for each TextBox, don't add that first event handler for TextBox_TextChanged, just add the line ..
lastTextBoxChangedName = sender.name
into each handler.

how to set minimum limit of a textbox vb.net

I need to set a minimum length for a password that can be used in a textbox and then set a label which will say if it meets the minimum number of characters required. I know how to set the limit of characters, what I can't do is the part where it will show in a label as soon as I leave the textbox. I was thinking I need to use an event, like maybe Leave or LostFocus, but it's not working. Please help :(
Ok, There are plenty of ways to do what you want to achieve. I personally like to a separate subroutine; if you need to change one thing, you wont have to edit every single event that has the same codeFrom what I can understand, something like this should help get you on your way. Basically, we just setup a subroutine that will check to see if textbox1.text's length is more than five and we trigger the subroutine by using events such as a button click of if the textbox is clicked off.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click ''save button
checkPassword(TextBox1.Text)
End Sub
Private Sub TextBox1_Leave(sender As Object, e As EventArgs) Handles TextBox1.Leave
checkPassword(TextBox1.Text)
End Sub
Private Sub checkPassword(password As String)
If Not password.Length > 5 Then
Label1.Text = "The password must be more than 5 charcharacters"
TextBox1.Clear()
Else
Label1.Text = "Password accepted"
End If
End Sub

vb.net add values from listbox to textbox via drag&drop AND via double click

I'm struggling with some functionality I want to use on my Windows form.
( Just for info, this is for an AutoDesk Inventor AddIn. )
This is my form layout.
The current workflow
The top 4 list-boxes are filled with available parameter names. The user chooses the parameter(s) he/she wants to use and drags and drops it into one of the driving parameter text-boxes ( marked with the <1> label ).
The code that relates to the drag and drop operations
Private Sub lstTemp_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) _
Handles lbModelParameters.MouseDown,
lbUserParameters.MouseDown,
lbReferenceParameters.MouseDown,
lbLinkedParameters.MouseDown
' In order to access a specific item in a listbox.itemcollection, you must think of it
' as an array of data or a collection and access it in the same manner by always
' letting VB know which item you intend to use by identifying it with its index location
' within the collection. And this is better than taking up basket weaving :-)
lbModelParameters.DoDragDrop(sender.Items(sender.SelectedIndex()).ToString, DragDropEffects.Move)
End Sub
Private Sub txtTemp_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) _
Handles tbParameter1.DragEnter,
tbParameter2.DragEnter,
tbParameter3.DragEnter,
tbParameter4.DragEnter,
tbParameter5.DragEnter
'Check the format of the incoming data and accept it if the destination control is able to handle
' the data format
'Data verification
If e.Data().GetDataPresent(DataFormats.Text) Then
e.Effect() = DragDropEffects.Move
Else
e.Effect() = DragDropEffects.None
End If
End Sub
Private Sub txtTemp_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) _
Handles tbParameter1.DragDrop,
tbParameter2.DragDrop,
tbParameter3.DragDrop,
tbParameter4.DragDrop,
tbParameter5.DragDrop
'This procedure receives the dragged data once it passes the data verification handled by the DragEnter method
'Drops the data onto the destination control
sender.Text() = e.Data().GetData(DataFormats.Text).ToString()
End Sub
New functionality
Now I would like to decrease the user mouse movement for ergonomic reasons and speed. But I would also like to keep to the drag and drop functionality. As it can overwrite a value that has already been added by the user.
I would like to be able to DoubleClick a item in the listbox, and that item should be added to the first empty textbox. I named my textboxes with a number so it's easy to loop over them all to check if it's empty.
I tried doing it with this code, but my double click event never gets fired. It always goes to the drag and drop. How do you do handle this, that the double click gets fired instead of drag drop?
Private Sub ParameterAddDoubleClick(sender As Object, e As EventArgs) _
Handles lbModelParameters.DoubleClick,
lbUserParameters.DoubleClick,
lbReferenceParameters.DoubleClick,
lbLinkedParameters.DoubleClick
Dim oControl As Windows.Forms.ListBox
oControl = DirectCast(sender, Windows.Forms.ListBox)
' Add line in likedparameters listbox
If oControl.SelectedIndex <> -1 Then
' Loop trough all the controls to see if one is empty
' if it's empty add parameter, else go to next
' if all textboxes are used do nothing.
For i = 1 To 6
Dim oTextbox As Windows.Forms.TextBox =
CType(gbDrivingParameters.Controls("tbParameter" & i),
Windows.Forms.TextBox)
If oTextbox.TextLength = 0 Then
' Add the sender item into the linked listbox
oTextbox.Text = oControl.Items.Item(oControl.SelectedIndex)
End If
Next
End If
End Sub
I hope my question is clear, and well prepared. If there is additional information needed, please let me know in a comment.
Mousedown triggers the DoDragDrop, wich stops the doubleclick-event from firing.
To identify if a user doubleclicks or wants to perform a dragdrop, consider the following:
Private Sub ListBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseDown
' Determine whether we are performing a drag operation OR a double click
If e.Clicks = 1 Then
TextBox1.Text = "mousedown"
Else
TextBox1.Text = "dblclick"
End If
End Sub

Capture keypress / let user pick their own start/stop key

Currently I have the start-key for my vb.net application hardcoded like this:
GetAsyncKeyState(Keys.F2)
Where vb.net sais "F2 As System.Windows.Forms.Keys = 113" on mouse-over
But I want my users to be able to pick their own Key. If I make a drop-down box (combobox) and pre-define some choices in there (Like ESC or F3), all those choices are strings. How can I convert those strings to a System.Windows.Forms.Keys integer?
Also, I'd like it to also be possible to "capture" a single keypress. So they'd click the "capture" button, and the next key they hit will be saved as the start/stop button. But I wouldn't even know where to begin looking for that one.
If txtKeys.Text=="F3" Then
GetAsyncKeyState(Keys.F3)
End If
Try something like this:
Public Class Form1
Dim captureKey As Boolean
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
captureKey = True
End Sub
Private Sub Button1_PreviewKeyDown(sender As Object, e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles Button1.PreviewKeyDown
If captureKey Then
Label1.Text = e.KeyValue.ToString
captureKey = False
End If
End Sub
End Class
I created a form with a label and a button for an example. e.KeyValue is an integer that I am converting to a string for display purposes. You also have the ability to capture other keydata. See this info on PreviewKeyDownEventArg
As for the first part of your question use a Select Case Statement to convert between your ComboBox Values and KeyData Values.