Creating/Deleting Objects via Checking if Toggles in CheckListBox in VB.Net - vb.net

I am playing around with some CheckedListItems in CheckBoxes and i am having issues with determining when a specific checked Product is checked and/or unchecked via its index position.
I know from MsgBox debugging that if i select either Product Allpurpose Cleaner or Cleaning Wipes it calls the MsgBoxes of both methods despite me attempting using logic to only execute for that specific Product. Somehow it thinks I have selected both items?
So essentially i am trying to do this:
If item zero in CheckedListBox is checked
Call conform menu to get desired amountand then come back to ordering menu.
ElseIF item zero in CheckedListBox is unchecked
Remove it from the current order.
This would essentially be rinse and repeat for all items in my CheckedListBox. I suspect VB.NET is causing my code to 'fall through' and it thinks all of the items i select are the same despite my attempts at preventing this.
May i please have some thoughts on this?
Thank you.
Private Sub CleaningProductsList_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CleaningProductsList.SelectedIndexChanged
Dim allPurposeCleaner = New AllPurposeCleaner()
Dim cleaningCloths = New cleaningCloths()
' If checked.
If CleaningProductsList.GetItemChecked(0) = True Then
isChecked = True
Me.Hide()
' MsgBox("All Purpose Cleaner Selected")
AmountMenue.setGivenProduct(allPurposeCleaner)
AmountMenue.Show()
' If unchecked.
ElseIf CleaningProductsList.GetItemChecked(0) = False Then
isChecked = False
' MsgBox("All Purpose Cleaner UnSelected ")
MsgBox(CleaningProductsList.GetItemChecked(0).ToString + " ALLPURPOSE UNCHECKED")
AmountMenue.removedGivenProduct(allPurposeCleaner)
End If
' If checked.
If CleaningProductsList.GetItemChecked(1) = True Then
Me.Hide()
AmountMenue.setGivenProduct(cleaningCloths)
MsgBox("cleaning cloths Selected ")
AmountMenue.Show()
' If unchecked.
ElseIf CleaningProductsList.GetItemChecked(1) = False And CleaningProductsList.CheckOnClick = False Then
MsgBox("cleaning cloths UnSelected ")
MsgBox(CleaningProductsList.GetItemChecked(2).ToString + " Cleaning Cloths UNCHECKED")
isChecked = False
AmountMenue.removedGivenProduct(cleaningCloths)
End If
End Sub

Here's an example of how you determine changes in a CheckedListBox:
Private checkedIndexes As New List(Of Integer)
Private checkedItems As New List(Of String)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CheckedListBox1.Items.AddRange({"First", "Second", "Third", "Fourth", "Fifth"})
End Sub
Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
If e.NewValue = CheckState.Checked Then
'An item is being checked.
checkedIndexes.Add(e.Index)
checkedItems.Add(CStr(CheckedListBox1.Items(e.Index)))
Else
'An item is being unchecked.
checkedIndexes.Remove(e.Index)
checkedItems.Remove(CStr(CheckedListBox1.Items(e.Index)))
End If
Label1.Text = $"Checked indexes: {String.Join(", ", checkedIndexes)}"
Label2.Text = $"Checked items: {String.Join(", ", checkedItems)}"
End Sub
The e parameter tells you what item is changing, via the Index property, and what it is changing from and to, via the CurrentValue and NewValue properties.
If you want to get a full list of checked items in that event handler, because the event is raised before the change is finalised, you need to start with the list provided by the control and then add or remove the current item:
Dim checkedItems = CheckedListBox1.CheckedItems.Cast(Of String)().ToList()
If e.NewValue = CheckState.Checked Then
checkedItems.Add(CStr(CheckedListBox1.Items(e.Index)))
Else
checkedItems.Remove(CStr(CheckedListBox1.Items(e.Index)))
End If
'Use checkedItems here.

Related

Selecting 1 Tool Strip Menu Item at any one time

I have a Tool strip menu with 4 options.
The options are degrees of screen rotation. (0, 90, 180, 270)
I am trying to select only 1 of these and keep it selected.
When I choose one then another, both are ticked (selected).
I have searched and found some solutions but only this works for me.
I have used the click event for each option to clear the ones not chosen like below.
Private Sub DegreesToolStripMenuItem6_Click(sender As Object, e As EventArgs) Handles DegreesToolStripMenuItem6.Click
DegreesToolStripMenuItem6.Checked = True
DegreesToolStripMenuItem7.Checked = False
DegreesToolStripMenuItem8.Checked = False
DegreesToolStripMenuItem9.Checked = False
End Sub
This sub is in my code 4 times to make it work but i'm sure there must be a cleaner, easier way to do this.
I have found online some other solutions but I can't seem to make it work, this one kind of makes sense like it should work but I can't figure it out
Private Sub DegreesToolStripMenuItem6_CheckedChanged(sender As Object, e As EventArgs) Handles DegreesToolStripMenuItem6.CheckedChanged, _
DegreesToolStripMenuItem7.CheckedChanged, _
DegreesToolStripMenuItem8.CheckedChanged, _
DegreesToolStripMenuItem9.CheckedChanged
Dim currentItem As ToolStripMenuItem = TryCast(sender, ToolStripMenuItem)
If currentItem IsNot Nothing AndAlso currentItem.Checked Then
Dim menu As ContextMenuStrip = TryCast(currentItem.Owner, ContextMenuStrip)
If menu IsNot Nothing Then
'The current item has just been checked so uncheck all other items on the same context menu strip.
For Each item As ToolStripMenuItem In menu.Items
If item IsNot currentItem Then
item.Checked = False
End If
Next item
End If
End If
End Sub
the toolstrip menu reads like this
-PreferedRotationToolStripMenuItem-DegreesToolStripMenuItem6
DegreesToolStripMenuItem7
DegreesToolStripMenuItem8
DegreesToolStripMenuItem9
Thanks for your time and looking forward to any help you guys can give.
Set CheckOnClick to True for each menu item, which I'm guessing you already have. This code worked for me:
Private Sub ToolStripMenuItems_CheckedChanged(sender As Object, e As EventArgs) Handles DegreesToolStripMenuItem9.CheckedChanged,
DegreesToolStripMenuItem8.CheckedChanged,
DegreesToolStripMenuItem7.CheckedChanged,
DegreesToolStripMenuItem6.CheckedChanged
Dim currentMenuItem = DirectCast(sender, ToolStripMenuItem)
If currentMenuItem.Checked Then
Dim menu = DirectCast(currentMenuItem.Owner, ContextMenuStrip)
For Each menuItem In menu.items.Cast(Of ToolStripMenuItem)
menuItem.Checked = menuItem Is currentMenuItem
Next
End If
End Sub
Here's a slight variation that avoids checking the already checked current item:
Private Sub ToolStripMenuItems_CheckedChanged(sender As Object, e As EventArgs) Handles DegreesToolStripMenuItem9.CheckedChanged,
DegreesToolStripMenuItem8.CheckedChanged,
DegreesToolStripMenuItem7.CheckedChanged,
DegreesToolStripMenuItem6.CheckedChanged
Dim currentMenuItem = DirectCast(sender, ToolStripMenuItem)
If currentMenuItem.Checked Then
Dim menu = DirectCast(currentMenuItem.Owner, ContextMenuStrip)
For Each menuItem In menu.Items.Cast(Of ToolStripMenuItem).Except({currentMenuItem})
menuItem.Checked = False
Next
End If
End Sub
The code above works if you have added the items to a ContextMenuStrip. If you have added them directly to an item on a MenuStrip then change this:
Dim menu = DirectCast(currentMenuItem.Owner, ContextMenuStrip)
to this:
Dim menu = DirectCast(currentMenuItem.Owner, ToolStripDropDownMenu)

Disable listview item in vb.net

I am trying to disable item (row) in my list view but its seem there no option like .enable = false and I tried to find anything to get my item to by disable but visible. Is there anything like that? If the user is allowed to select it then the item is enabled else it's visible but not enabled.
I have a table in the database that admin will fill it in which the user can view the window or not, so I want the user to able to see it and if not allowed to view it then its disable.
This only works if MultiSelect is set to False and the .Tag property is set for every item. (Yes or No).
Private Sub ListView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListView1.SelectedIndexChanged
If Not ListView1.SelectedItems.Count = 0 Then
Dim item As ListViewItem = ListView1.SelectedItems(0)
If item.Tag.ToString = "No" Then
item.Selected = False
End If
End If
End Sub
As per # jmcilhinney , The following code should work with MultiSelect = True. I tried to access the last item added to the collection but it seems that the SelectedItems collection is ordered the same as the order the items appear in the ListView; not as expected the last item added would be last in the collection..
Private Sub ListView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListView1.SelectedIndexChanged
If Not ListView1.SelectedItems.Count = 0 Then
For Each item As ListViewItem In ListView1.SelectedItems
If item.Tag.ToString = "No" Then
item.Selected = False
End If
Next
End If
End Sub

Visual Basic- Loop to make listbox update as checkbox is checked

I'm having trouble having the listbox update as the checkbox is checked. I have a total of 8 "test_location" check boxes and I want the listbox to add items to "Steps_Queue_List" and store "1" in the "Test_Locations" array when the location is checked. Also want to clear the list when the checkbox is unchecked. This works so far but I would much prefer to learn how to make a loop for this:
Private Sub Location_CheckBox_1_CheckedChanged(sender As Object, e As EventArgs) Handles Location_CheckBox_1.CheckedChanged
If Location_CheckBox_1.Checked Then
Test_Locations(0) = 1
Steps_Queue_List.Items.Add("test for location" & 1, 1)
ElseIf Location_CheckBox_1.Checked = False Then
Test_Locations(0) = 0
Steps_Queue_List.Items.RemoveAt(0)
End If
End Sub
Private Sub Location_CheckBox_2_CheckedChanged(sender As Object, e As EventArgs) Handles Location_CheckBox_2.CheckedChanged
If Location_CheckBox_2.Checked Then
Test_Locations(1) = 1
Steps_Queue_List.Items.Add("test for location" & 2, 2)
ElseIf Location_CheckBox_2.Checked = False Then
Test_Locations(1) = 0
Steps_Queue_List.Items.RemoveAt(0)
End If
End Sub
Private Sub Location_CheckBox_3_CheckedChanged(sender As Object, e As EventArgs) Handles Location_CheckBox_3.CheckedChanged
If Location_CheckBox_3.Checked Then
Test_Locations(2) = 1
Steps_Queue_List.Items.Add("test for location" & 3, 3)
ElseIf Location_CheckBox_3.Checked = False Then
Test_Locations(2) = 0
Steps_Queue_List.Items.RemoveAt(0)
End If
End Sub
Thanks in advance.
You don't need a loop but you can just handle everything in a single method.
Set the property Tag of your Checkboxes to a progressive value starting from 1 to 8 matching the text value you want to be displayed in the listboxes.
Then setup an event handler that manages all the CheckBoxChanged events for all the CheckBox.
In this event handler retrieve the tag and use it to address the array index and the listbox to update
' Handle all Checkbox changed with the same handler
Private Sub OnCheckBoxChanged(sender As Object, e As EventArgs)
Handles Location_CheckBox_1.CheckedChanged,Location_CheckBox_2.CheckedChanged,
Location_CheckBox_3.CheckedChanged,Location_CheckBox_4.CheckedChanged,
Location_CheckBox_5.CheckedChanged,Location_CheckBox_6.CheckedChanged,
Location_CheckBox_7.CheckedChanged,Location_CheckBox_8.CheckedChanged
' Discover which checkbox has been clicked
Dim chk = DirectCast(sender, CheckBox)
' Now read the value of the Tag property of that checkbox
Dim idx = Convert.ToInt32(chk.Tag)
If chk.Checked Then
Test_Locations(idx - 1) = 1
Steps_Queue_List.Items.Add("test for location" & idx, idx)
Else
Test_Locations(idx - 1) = 0
Steps_Queue_List.Items.RemoveAt(0)
End If
End Sub

AutoComplete Textbox to detect if text is typed from user or appended from AutoComplete collection?

I have created an autocomplete textbox with mode of SuggestAndAppend text. I would like to detect if the text in the textbox is newly typed by user, or it is just appended from the Source Collection?
it can be checked when the textbox loose focus, but is there another way to detect immediately as the focus still in the textbox?
any idea?
for the time being, I could write a code to implement the task. right now, this code can detect if the newly typed text is not a part of any items in the collection. but what if the user typed a newly text which can be considered as a part of an entry in the collection? i.e what if the collection contains entries like : BBC, CNN, FOX New and user wants to type only CN ( Cartoon Network)..in this case "CN" will be a part of CNN and then the code will not detect it as a new entry.
Private Sub TextBox1_TextChanged_1(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Dim isNew As Boolean = True
For i As Integer = 0 To TextBox1.AutoCompleteCustomSource.Count - 1
If UCase(Trim(TextBox1.AutoCompleteCustomSource(i))) Like UCase(Trim(TextBox1.Text)) & "*" Then
isNew = False
Exit For
End If
Next
If isNew = True Then
MsgBox("Custome")
Else
End If
End Sub
the below code can chick if the text in textbox is new to collection or no, for the time being, it catch it in Leave Event. it should be improved to catch [Enter] key as well
Private Sub TextBox1_Leave(sender As Object, e As EventArgs) Handles TextBox1.Leave
Dim isNew As Boolean = True
For i As Integer = 0 To TextBox1.AutoCompleteCustomSource.Count - 1
If TextBox1.AutoCompleteCustomSource.Contains(UCase(Trim(TextBox1.Text))) Then
isNew = False
End If
Next
If isNew = True Then
MsgBox("Custome")
Else
End If
End Sub

Data doesn't display when working with multiple forms

I'm new to VB.NET and have been struggling all afternoon with something. I've found similar questions on the forum but none of them seemed to describe my problem exactly. I'm fairly sure that I'm missing something very basic.
I have made a main form which currently holds only one button which purpose is to open up a second form and close the main form. Based on the settings the user will select on the 2nd form the first form might have to be adapted to match with the new settings. But the problem occurs even before that.
The 'settings' form has 15 textboxes which I drew onto the form in development mode. They are called ID1, ID2,..,ID15. The values which I want to display in there are saved in an array:
Dim ids(15) as integer
Next, I created a module to simulate what you could call a control array as I used to use them in VB6.
Public sources() As TextBox = [frmSettings.ID1, frmSettings.ID2, //and so on
I did this to be able to iterate through all the 15 textboxes:
For i = 0 To 14
Sources(i).Text = ids(i + 1)
Next
Then I added on the main form this code to the Button1_Click() event:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
frmSettings.Show()
Me.Close()
End Sub
I did the same thing for the 'exit ' button on the frmSettings form.
This seems to work, but only once. I launch the application, push the button and frmSettings pops up and shows all the values from the array in the textboxes. When I push the 'close' button, I return to the main page.
So far so good, but if I try to return to frmSettings a second time, all the textboxes remain blank as if the code I added to the form never gets executed.
Any help would be greatly appreciated!
First, make sure the array that holds your data is accessible to both forms:
Module Module1
Public ids(15) As Integer
End Module
There should not be a declaration for "ids" in either form.
Next, make frmSettings itself responsible for loading and saving the data:
Public Class frmSettings
Private Sub frmSettings_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim matches() As Control
For i As Integer = 0 To 14
matches = Me.Controls.Find("ID" & (i + 1), True)
If matches.Length > 0 AndAlso TypeOf matches(0) Is TextBox Then
Dim TB As TextBox = DirectCast(matches(0), TextBox)
TB.Text = ids(i)
End If
Next
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim valid As Boolean = True
Dim matches() As Control
For i As Integer = 0 To 14
matches = Me.Controls.Find("ID" & (i + 1), True)
If matches.Length > 0 AndAlso TypeOf matches(0) Is TextBox Then
Dim TB As TextBox = DirectCast(matches(0), TextBox)
Dim value As Integer
If Integer.TryParse(TB.Text, value) Then
ids(i) = value
Else
MessageBox.Show(TB.Name & ": " & TB.Text, "Invalid Value", MessageBoxButtons.OK, MessageBoxIcon.Warning)
valid = False
End If
End If
Next
If valid Then
Me.Close()
End If
End Sub
End Class