VB GetAsyncKeyState, combobox selected keys - vb.net

I'm trying to do an action, when specific keys, selected by the user, are pressed.. but I don't know how to do It.
Is there any easiest way to to this:
If ComboBox1.SelectedItem = "F8"
If GetAsyncKeyState(Keys.F8) Then
'something
End If
ElseIf ComboBox1.SelectedItem = "F9"
If GetAsyncKeyState(Keys.F9) Then
'something
End If
ElseIf ComboBox1.SelectedItem = "F10"
If GetAsyncKeyState(Keys.F10) Then
'something
End If
End If
'and other more..
I tried
Dim asd as String
asd = ComboBox1.Text
If ComboBox1.Text Then
If GetAsyncKeyState(Keys.kj) Then
'something
End If
End If

One simple way is to put everything in a Dictionary, using it you can check the specified keyboard key by the Dictionary key.
First, declare this at class level (outside any sub or function):
Dim Hotkeys As New Dictionary(Of String, Keys) From { _
{"F8", Keys.F8}, _
{"F9", Keys.F9}, _
{"F10", Keys.F10} _
}
Then when you are going to check if the specified key was pressed you'd just do:
If GetAsyncKeyState(Hotkeys(ComboBox1.SelectedItem.ToString())) Then
'Some code here
End If
To add more keys you just keep adding rows to the Dictionary.
{"<key alias>", Keys.<key value>}, _
<key alias> (without the <> brackets) must be exactly the same as the respective item in the ComboBox.
And a final note: every row should end with }, _ except for the last one, which includes no comma } _.
Hope this helps!

Related

How to remove and re-add a comma in a string?

I have a textbox on my form that when a button is clicked, it is populated with numbers that are separated by a comma. I have a delete button that will remove the numbers with the comma one at a time. My question is how would I go about re-adding the comma every time i hit the add button, again? I thought i could add the comma in the beginning in an if statement, but its adding two commas, every time I hit the add button, if I delete, then try to re- add.
here is what i have :
if textbox1.text = "" then
textbox1.text = textbox1.text & testNumber(combobox.selecteditem) & ","
else
textbox1.text = "," & textbox1.text & testnumber(combox.selecteditem)
end if
The contents of the textbox should only be a view of a more appropriate underlying data structure. For example, you might have a List(Of Integer) or Queue(Of Integer) as a member of your form. When you add or remove an item you first update the collection, then you set the text. For example:
Add:
MyList.Add(nextNumber)
textbox1.text = String.Join(","c, MyList)
Remove:
MyList.RemoveAt(MyList.Count - 1);
textbox1.text = String.Join(","c, MyList)
Do this even if they want the ability to update the textbox directly. It's just in this case you must also be able to validate and parse the contents of the textbox to recreate the list.
First of all, storing numbers in a comma delimited string is pretty strange requirement. I'd suggest to store numbers in a proper data type, such as: List(Of Integer).
Assuming that testnumber function returns integer...
'define at the top of Form's module:
Private myNumbers As List(Of Integer) = New List(Of Integer)()
'copy-paste below method to the form's module
Private Function GetCommaSeparatedNumbers() As String
Return String.Join(",", myNumbers)
End Function
'finally:
'to add number
myNumbers.Add(testnumber(combox.selecteditem))
'to remove number
myNumbers.Remove(testnumber(combox.selecteditem))
'to display numbers
Me.textbox1.Text = GetCommaSeparatedNumbers()
If you would like to check out if number already exists on the list, use:
If myNumbers.Contains(testnumber(combox.selecteditem)) Then
'display warning
Else
'add number
End If
Good luck!
Your code is initial testing textbox1.Text = "" and then, if that is true, it is then doing textbox1.Text = textbox1.Text & testNumber(combobox.SelectedItem) & ",", but since textbox1.Text is "" this is the equivalent of:
textbox1.Text = "" & testNumber(combobox.SelectedItem) & ","
That really means you are adding a comma when you only have one number.
This is what you should be doing:
if textbox1.Text = "" then
textbox1.Text = testNumber(combobox.SelectedItem)
else
textbox1.Text = textbox1.Text & "," & testnumber(combox.SelectedItem)
end if
To add a number, I'd do it with this line:
TextBox1.AppendText(If(TextBox1.TextLength = 0, "", ",") & testNumber(ComboBox.SelectedItem))
Are numbers being deleted from the beginning or end?...or is a "selected" number from anywhere in the list being deleted?

retain the value which I checked in a box in a datagridview using vb.net

Good Day to everybody.
I ran out of ideas so I'm posting this to SO, I want to create a form where users can search for records, then tik check on the datagrid view, then retain the check even though they used.
In this illustration the user searched for a certain number then selected it, its the bottom one.
I would want it that if the user would like to search for another record, the item wont be removed.
in this illustration, the item was removed because the use searched for another record.
My current work is the following
Private Sub dgvConfirm_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvConfirm.CellContentClick
If dgvConfirm.Item(0, dgvConfirm.CurrentRow.Index).Value = 0 Then
dgvConfirm.Item(0, dgvConfirm.CurrentRow.Index).Value = 1
nmblst = nmblst + dgvConfirm.Item(2, dgvConfirm.CurrentRow.Index).Value + ","
Else
dgvConfirm.Item(0, dgvConfirm.CurrentRow.Index).Value = 0
End If
End Sub
this is the code when I clicked the datagridview, it just gets the unique key column and transfers it into a string.
Private Sub txtSearch_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged
If nmblst <> "" Or nmblst.Length > 0 Then
nmblst = nmblst.Trim().Remove(nmblst.Length - 1)
scndQry = " or PPFNo in ('%" & nmblst & "%') "
End If
If rdoPartNo.Checked = True Then
bndsrc.Filter = "PartNo Like '%" & txtSearch.Text & "%' " + scndQry
Else
bndsrc.Filter = "PPFNo Like '%" & txtSearch.Text & "%' " + scndQry
End If
frstQry = bndsrc.Filter
End Sub
This code is for searching. I am trying to use something like select this from thistable where columnname like '%something%' and columname in (etc,etc) do take note that columnname and columnname are the same.
Is there a property of datagridview for what I need?
I think that you are approaching this problem incorrectly.
Assuming that only one item can be checked, try storing the checked row in a type, with each column stored separately, like this:
Private Type temp
PartNo As Long
PPFNo As Integer
ProductNo As String
DateCreated As DateTime
And so on...
End Type
When something is checked, you find the row on which the box is checked, and then you put each field in the temp type, something like this:
For i = 0 to DataGridView.Columns - 1
temp(i) = DataGridView.Item(i, selectedrow).Value
Loop
Then, at the end of your search, you can append your temp to the DataGridView by adding the following to your code:
DataGridView.Rows.Add(temp(0),temp(1),temp(2),temp(3)) 'And more if you have more columns
Good luck with your problem and I hope my answer helps :)

How do I compare two listboxes?

I have two listboxes (1: Primary, 2:Secondary).
These listboxes contain numbers. The Primary Listbox contains 7 numbers, and the Secondary Listbox contains 6 numbers.
I want to compare the values of the Primary Listbox to those of the Secondary.
This comparison should yield three results:
Result #1:
X number of values were found to be common.
Result#2:
All numbers matched.
Result#3:
No matches found.
This is what I have so far:
If lstPrimaryNumbers.Items.Count = 0 Or lstSecondaryNumbers.Items.Count = 0 Then
MessageBox.Show("There is nothing to compare.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
For i As Integer = 0 To lstPrimaryNumbers.Items.Contains
For j As Integer = 0 To lstSecondaryNumbers.Items.Contains
If i = j Then
MessageBox.Show(i & " " & j & " matched!")
End If
Next
Next
PLEASE NOTE:
I HAVE CHANGED MY ENTIRE INTERFACE, SO THIS POST IS OBSOLETE AND I HAVE NO USE FOR IT NOW. THANK YOU EVERYONE FOR YOUR SUPPORT!
I will leave this for the moderators to decide whether to remove this post or keep it for other users reference.
I will flag this post.
The matching items could be found with
Dim r = lb1.Items.Cast(Of Int32).Where(Function (x) lb2.Items.Contains(x))
MessageBox.Show(String.Join(",", r) & " matched")
If you want to have a full match, then use IEnumerable.All to check
Dim a = lb1.Items.Cast(Of Int32).All(Function (x) lb2.Items.Contains(x))
If a Then
MessageBox.Show("Full Match")
End If
Finally if you want only know if some items match then use IEnumerable.Any
Dim b = lb1.Items.Cast(Of Int32).Any(Function(x) lb2.Items.Contains(x))
If Not b Then
MessageBox.Show("No matches where found")
End If
I have assumed that your items are integers, but if you add them as strings then you need to change the Cast(Of Int32) to Cast(Of String)
First, I got the contents of the ListBoxes into arrays with a little linq. Then using the .Intersect method found the matches. And displayed the .Count. You iterate the result with a For Each
Private Sub OPCode()
Dim id1() As Integer = (From i In ListBox1.Items Select CInt(i)).ToArray
Dim id2() As Integer = (From i In ListBox2.Items Select CInt(i)).ToArray
Dim Matches As IEnumerable(Of Integer) = id1.Intersect(id2)
MessageBox.Show(Matches.Count.ToString)
End Sub
'TextBox1.Multiline = True is set at design time
'Expand the text box size so several lines will be visible
For Each Match As Integer In Matches
TextBox1.Text &= (CStr(Match) & Environment.NewLine)
Next

How can i check for a character after certain text within a listbox?

How can i check for a character after other text within a listbox?
e.g
Listbox contents:
Key1: V
Key2: F
Key3: S
Key4: H
How do I find what comes after Key1-4:?
Key1-4 will always be the same however what comes after that will be user defined.
I figured out how to save checkboxes as theres only 2 values to choose from, although user defined textboxes is what im struggling with. (I have searched for solutions but none seemed to work for me)
Usage:
Form1_Load
If ListBox1.Items.Contains("Key1: " & UsersKey) Then
TextBox1.Text = UsersKey
End If
Which textbox1.text would then contain V / whatever the user defined.
I did try something that kind of worked:
Form1_Load
Dim UsersKey as string = "V"
If ListBox1.Items.Contains("Key1: " & UsersKey) Then
TextBox1.Text = UsersKey
End If
but i'm not sure how to add additional letters / numbers to "V", then output that specific number/letter to the textbox. (I have special characters blocked)
Reasoning I need this is because I have created a custom save settings which saves on exit and loads with form1 as the built in save settings doesn't have much customization.
e.g Can't choose save path, when filename is changed a new user.config is generated along with old settings lost.
Look at regular expressions for this.
Using the keys from your sample:
Dim keys As String = "VFSH"
Dim exp As New RegEx("Key[1-4]: ([" & keys& "])")
For Each item As String in ListBox1.Items
Dim result = exp.Match(item)
If result.Success Then
TextBox1.Text = result.Groups(1).Value
End If
Next
It's not clear to me how your ListBoxes work. If you might find, for example, "Key 2:" inside ListBox1 that you need to ignore, you will want to change the [1-4] part of the expression to be more specific.
Additionally, if you're just trying to exclude unicode or punctuation, you could also go with ranges:
Dim keys As String = "A-Za-z0-9"
If you are supporting a broader set of characters, there are some you must be careful with: ], \, ^, and - can all have special meanings inside of a regular expression character class.
You have multiple keys, I assume you have multiple textboxes to display the results?
Then something like this would work. Loop thru the total number of keys, inside that you loop thru the alphabet. When you find a match, output to the correct textbox:
Dim UsersKey As String
For i As Integer = 1 To 4
For Each c In "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray()
UsersKey = c
If ListBox1.Items.Contains("Key" & i & ": " & UsersKey) Then
Select Case i
Case 1
TextBox1.Text = UsersKey
Case 2
TextBox2.Text = UsersKey
Case 3
TextBox3.Text = UsersKey
Case 4
TextBox4.Text = UsersKey
End Select
Exit For 'match found so exit inner loop
End If
Next
Next
Also, you say your settings are lost when the filename is changed. I assume when the version changes? The Settings has an upgrade method to read from a previous version. If you add an UpgradeSettings boolean option and set it to True and then do this at the start of your app, it will load the settings from a previous version:
If My.Settings.UpgradeSettings = True Then
My.Settings.Upgrade()
My.Settings.Reload()
My.Settings.UpgradeSettings = False
My.Settings.Save()
End If
Updated Answer:
Instead of using a listtbox, read the settings file line by line and output the results to the correct textbox based on the key...something like this:
Dim settingsFile As String = "C:\settings.txt"
If IO.File.Exists(settingsFile) Then
For Each line As String In IO.File.ReadLines(settingsFile)
Dim params() As String = Split(line, ":")
If params.Length = 2 Then
params(0) = params(0).Trim
params(1) = params(1).Trim
Select Case params(0)
Case "Key1"
Textbox1.Text = params(1)
Case "Key2"
Textbox2.Text = params(1)
End Select
End If
Next line
End If
You can associate text box with a key via its Name or Tag property. Lets say you use Name. In this case TextBox2 is associated with key2. TextBox[N] <-> Key[N]
Using this principle the code will look like this [considering that your list item is string]
Sub Test()
If ListBox1.SelectedIndex = -1 Then Return
Dim data[] As String = DirectCast(ListBox1.SelectedItem, string).Split(new char(){":"})
Dim key As String = data(0).Substring(3)
Dim val As String = data(1).Trim()
' you can use one of the known techniques to get control on which your texbox sits.
' I omit this step and assume "Surface1" being a control on which your text boxes sit
DirectCast(
(From ctrl In Surface1.Controls
Where ctrl.Name = "TextBox" & key
Select ctrl).First()), TextBox).Text = val
End Sub
As you can see, using principle I just explained, you have little parsing and what is important, there is no growing Select case if, lets say, you get 20 text boxes. You can add as many text boxes and as many corresponding list items as you wish, the code need not change.

How can I distinguish the text displayed in a listbox from a real value.?

I have a listbox with multiselect options. I populate it using the addItem function.
I can't find any article about this on Google, but I need to distinguish from the text displayed in the listbox and a real value.
For example:
shown hiddenvalue
-------- -----------
monday A1
tuesday A2
wednesday C7
etc.
Is it possible? How can I access these values?
For VBA listbox you want to:
Declare two columns (ColumnCount = 2).
Make the second one hidden: ColumnWidths = ";0".
Declare the second column as bound (BoundColumn = 2) and the first column as textual (TextColumn = 1).
Have a procedure to add values:
Private Sub AddWithID(Text As String, ID As String)
ListBox1.AddItem Text
ListBox1.List(ListBox1.ListCount - 1, 1) = ID
End Sub
Now, for single-select listbox, you can use .Value or .Text to find out selected value/text.
For multi-select listbox, you can use .List(i, 0) for text and .List(i, 1) for value, where i in an index of a row.
Another way... Using Collections.
Private HiddenValue As New Collection
Private Sub CommandButton1_Click()
AddItems "monday", "A1"
AddItems "tuesday", "A2"
AddItems "wednesday", "C7"
End Sub
Private Sub CommandButton2_Click()
MsgBox "Shown Value :" & ListBox1.List(ListBox1.ListIndex) & vbNewLine & _
"Hidden Value " & HiddenValue(ListBox1.ListIndex + 1)
End Sub
Private Sub AddItems(Text As String, ID As String)
ListBox1.AddItem Text
HiddenValue.Add ID
End Sub
SNAPSHOTS