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

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

Related

Add CheckBox To DataGridView Cell Programmatically

I’m trying to add a CheckBox programmatically to a DataGridVew cell if the cell next to it has a value of “1”. I’m trying to do this as the rows are added
I’m hoping someone can help me out with the correct code here. I understand one of the lines of code is incorrect but I’ve put it in to illustrate what I'm trying to do.
Thanks in advance.
Private Sub Controls_DGV_RowsAdded(sender As Object, e As Windows.Forms.DataGridViewRowsAddedEventArgs) Handles Controls_DGV.RowsAdded
If Controls_DGV.Rows(e.RowIndex).Cells(2).Value = "1" Then
Controls_DGV.Rows(e.RowIndex).Cells(1).AddCheckBox ' THIS LINE IS INCORRECT
End If
End Sub
This is the same as #miguel except for the checking the value, in this case Option Strict is On as it should be.
Public Class Form1
Private Sub dataGridView1_RowsAdded(sender As Object, e As DataGridViewRowsAddedEventArgs) _
Handles dataGridView1.RowsAdded
If CStr(dataGridView1.Rows(e.RowIndex).Cells(1).Value) <> "1" Then
dataGridView1.Rows(e.RowIndex).Cells(0).Value = False
dataGridView1.Rows(e.RowIndex).Cells(0) = New DataGridViewTextBoxCell()
dataGridView1.Rows(e.RowIndex).Cells(0).Value = ""
dataGridView1.Rows(e.RowIndex).Cells(0).ReadOnly = True
End If
End Sub
Private Sub AddRowsButton_Click(sender As Object, e As EventArgs) _
Handles AddRowsButton.Click
For index As Integer = 0 To 5
If CBool(index Mod 2) Then
dataGridView1.Rows.Add(False, "0")
Else
dataGridView1.Rows.Add(False, "1")
End If
Next
End Sub
End Class
The column number 1 that you want to display a checkbox should already be of type DataGridViewCheckBoxColumn and then if the value is not "1" you can transform the type of the cell for a DataGridViewTextBoxCell, so there is no checkbox and you can even put there some text if you want. Because you're using 3 columns, i'll try to do the same.
In your Form1_Load() you should have something like this if you are adding columns programmatically:
Dim ChkBox As New DataGridViewCheckBoxColumn
Controls_DGV.Columns.Add("TextBox1", "TextBox1")
Controls_DGV.Columns.Add(ChkBox)
Controls_DGV.Columns.Add("TextBox2", "TextBox2")
Then using your code it should be like this:
Private Sub Controls_DGV_RowsAdded(sender As Object, e As Windows.Forms.DataGridViewRowsAddedEventArgs) Handles Controls_DGV.RowsAdded
If Controls_DGV.Rows(e.RowIndex).Cells(2).Value <> "1" Then
' replace the checkbox cell by textbox cell
Controls_DGV.Rows(e.RowIndex).Cells(1) = New DataGridViewTextBoxCell()
Controls_DGV.Rows(e.RowIndex).Cells(1).Value = "(empty or some text)"
End If
End Sub

Creating/Deleting Objects via Checking if Toggles in CheckListBox in 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.

Combo Box Returning -1 For SelectedIndex

I'm trying to pick up a combo box's selected index. This was working absolutely fine, then all of a sudden it started returning -1 no matter what item is selected
My code is:
Form Code
Private Sub Man_SelectedIndexChanged_1(sender As Object, e As EventArgs) Handles Man.SelectedIndexChanged, Units.SelectedIndexChanged
'Set Transducer Type
Call References.LevListAdd()
End Sub
References Module LevListAdd Sub
Public Sub LevListAdd()
Form1.Lev.Items.Clear()
If Form1.Man.Text = "Pulsar" Then
With Form1.Lev.Items
.Add("Ultra Range")
.Add("IMP Range")
.Add("Twin Range")
End With
End If
End Sub
This fills the combo box lev fine when the Man combo box item "Pulsar" is selected. I then want my users to click a button to generate some labels and stuff. The code is as such:
Button Click Code
Private Sub Generate_Click(sender As Object, e As EventArgs) Handles Generate.Click
If CheckGenerate() = False Then Exit Sub
Dim X = CheckGenerationType(Man.SelectedIndex, Lev.SelectedIndex, Level.Checked, Volume.Checked, ListBox1.SelectedIndex,
Units.SelectedIndex)
Call ParamPage(X)
End Sub
CheckGenerate simply checks that all boxes have been filled in. I pass the informtion from the form to the following function:
Public Function CheckGenerationType(Man As Integer, Lev As Integer, Level As Boolean, Volume As Boolean, TankType As Integer,
MeasurementUnit As Integer) As String
Dim M As Integer
Dim L As Integer
Dim CT As Integer
Dim TT As Integer
Dim Ms As Integer
M = Man
L = Lev
TT = TankType
Ms = MeasurementUnit
If Level = True Then
CT = 0
ElseIf Volume = True Then
CT = 1
End If
CheckGenerationType = CStr(M) + "." + CStr(L) + "." + CStr(CT) + "." + CStr(TT) + "." + CStr(Ms)
End Function
When the lev.selectedindex parameter arrives at this function, it reads -1. Even if the user has selected any of the 3 items. Can anyone explain why this is happening?
I've just tried your code. I get the same result (-1 in lev.SelectedIndex) and this was because jumped using tab through the controls my when i'm hitting the Man or Units Combobox it runs the LevListAdd() and then clears the Lev-ComboBox because of Form1.Lev.Items.Clear().
You should think about your call Man_SelectedIndexChanged_1 or maybe just use something like this:
Public Sub LevListAdd()
If Form1.Man.Text = "Pulsar" Then
Form1.Lev.Items.Clear()
instead of
Public Sub LevListAdd()
Form1.Lev.Items.Clear()
If Form1.Man.Text = "Pulsar" Then
And you should separate the calls from the man and unit ComboBoxes.
Private Sub Unit_SelectedIndexChanged_1(sender As Object, e As EventArgs) Handles Units.SelectedIndexChanged
' Do something
End Sub
Private Sub Man_SelectedIndexChanged_1(sender As Object, e As EventArgs) Handles Man.SelectedIndexChanged
Form1.Lev.Items.Clear()
Select Case Form1.Man.Text
Case "Pulsar"
With Form1.Lev.Items
.Add("Ultra Range")
.Add("IMP Range")
.Add("Twin Range")
End With
Case "animals"
With Form1.Lev.Items
.Add("dogs")
.Add("cats")
.Add("birds")
End With
End Select
End Sub

VB, Pass variables to a control

I have been tasked with creating a cinema booking system in VB.net by my teacher. So far I have created 50 CheckBoxes and I am trying to rename them all to seat (number). I have this code in my Form1.load but it is not working because it is a type and not an expression. I tried using a variable for this but it did not work.
Here is my code:
For count As Integer = 1 To 54 Step 1
CheckBox(count).text = "Seat " & count
Next
Please help, and or recommend me another way to accomplish this.
set the name of the checkbox when you create it. To find out how to create a checkbox programmatically add a checkbox to a form then look at .designer.vb
dim cb as new checkbox
cb.name = "1"
cb.text = "Seat 1"
you need to also add the location and other properties
If you have already created your textboxes with names like 1, 2 then iterate through and get the numbers like this: If you call them CB_1 then cut the CB_ off before looking for the number.
dim cbNumber as int16
For Each c As Control In myContainer.Controls
If c.GetType() Is GetType(CheckBox) Then
cbnumber = cint(c.name)
c.text = "Seat" & cbnumber
End If
Next
Well, here's my approach. In order to test just drop on a FlowLayoutPanel, a Button, and a NumericUpDownonto the form.
Option Strict On
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For count As Integer = 1 To 54 Step 1
' Make a new CheckBox
Dim chkBox As New CheckBox()
' Setup the Checkbox
With chkBox
.Tag = count.ToString
.Name = CStr("seatCheckBox" & count.ToString)
.Text = String.Format("Seat {0}", count)
.ThreeState = False
.Checked = False
End With
' add an event listener for the checkbox checkstate changed event
AddHandler chkBox.CheckStateChanged, AddressOf Me.CheckBox_CheckStateChanged
' Add the checkbox to the control
Me.FlowLayoutPanel1.Controls.Add(chkBox)
' Keep the user from picking something that doesn't exist
Me.NumericUpDown1.Maximum = CDec(count)
Next
' Add and event listener for the find button click event
AddHandler Button1.Click, AddressOf Me.FindButton_Clicked
End Sub
' Find the checkbox in the form and return it
Private Function GetCheckBox(ByVal seatNumber As Integer) As CheckBox
Dim chkbox As CheckBox
' Try to find the Checkbox
Try
chkbox = TryCast(Me.Controls.Find(CStr("seatCheckBox" & seatNumber.ToString), True).First, CheckBox)
Catch ex As Exception
chkbox = Nothing
End Try
'Check if the trycast worked
If IsNothing(chkbox) Then
Throw New ArgumentOutOfRangeException("seatNumber", "The seat number to be searched for was not found")
Else
Return chkbox
End If
End Function
' Handle the Chekbox checkState event.
Private Sub CheckBox_CheckStateChanged(sender As Object, e As EventArgs)
' Convert to Checkbox
Dim chkBox As CheckBox = DirectCast(sender, CheckBox)
' Simple result string
Dim resultstring As String = CStr("Seat Number {0} is now {1}.")
' Set the values
Select Case chkBox.Checked
Case True
resultstring = String.Format(resultstring, chkBox.Tag, "taken")
Case False
resultstring = String.Format(resultstring, chkBox.Tag, "available")
End Select
' Display it
MsgBox(resultstring)
End Sub
Private Sub FindButton_Clicked(sender As Object, e As EventArgs)
Try
' Get the checkbox and return it's name
MsgBox(GetCheckBox(CInt(Me.NumericUpDown1.Value)).Name.ToString)
Catch ex As Exception
' Display the error
MsgBox(ex.Message)
End Try
End Sub
End Class

Checkbox returned in Event Handler isn't one on form

I'm creating an array of checkboxes on a form dynamically; the code that creates the array looks like this:-
checkbox_array(count_of_checkboxes) = New CheckBox
if (count_of_checkboxes = 0) Then
checkbox_array(count_of_checkboxes).Top = specimen_checkbox.Top
checkbox_array(count_of_checkboxes).Left = specimen_checkbox.Left
else
checkbox_array(count_of_checkboxes).Top = checkbox_array(count_of_checkboxes - 1).Top + vertical_offset
checkbox_array(count_of_checkboxes).Left = checkbox_array(count_of_checkboxes - 1).Left + horizontal_offset
End If
my_panel.Controls.Add(checkbox_array(count_of_checkboxes))
AddHandler checkbox_array(count_of_checkboxes).MouseClick, cbxSpecimen_CheckedChanged
checkbox_array(count_of_checkboxes).Name = someValue
checkbox_array(count_of_checkboxes).Text = someValue
checkbox_array(count_of_checkboxes).Enabled = true
checkbox_array(count_of_checkboxes).Visible = true
checkbox_array(count_of_checkboxes).Show()
This works fine and dandy on one form. However, I am using the same code on a form which is derived from a base form, and running into a problem, in that the object returned in the sender parameter, although clearly a checkbox with a recognisable name, isn't any of the checkboxes in the array.
I verified this with:-
Private Sub cbxSpecimen_CheckedChanged( sender As System.Object, e As System.EventArgs) Handles cbxSpecimen.CheckedChanged
For i As Integer = 0 To checkbox_array.GetUpperBound(0) - 1
If checkbox_array(i).Equals(sender) Then
// set a breakpoint here
End If
Next i
End Sub
Can anyone shed any light on why this should work on a normal form, but not a derived-class form?
I verified this with:-
Private Sub cbxSpecimen_CheckedChanged( sender As System.Object, e As System.EventArgs)
Handles cbxSpecimen.CheckedChanged
For i As Integer = 0 To checkbox_array.GetUpperBound(0) - 1
If checkbox_array(i).Equals(sender) Then
// set a breakpoint here
End If
Next i
End Sub
Why checkbox_array.GetUpperBound(0) - 1? This will skip the last element in the array. Try:
For i As Integer = 0 To checkbox_array.GetUpperBound(0)
If checkbox_array(i).Equals(sender) Then
// set a breakpoint here
End If
Next i
Or
For i As Integer = 0 To checkbox_array.Length - 1
...
I have managed to get this to work by refilling the array of checkboxes inside the click event:-
Private Sub cbxSpecimen_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles cbxSpecimen.CheckedChanged
For i As Integer = 0 To check_boxes.GetUpperBound(0)
If check_box_array(i).Name = CType(sender, CheckBox).Name And
Not check_box_array(i).Equals(sender) Then
check_box_array(i) = CType(sender, CheckBox)
End If
Next i
' do useful work
End Sub
After the check box on the form has been stuffed back into the array, it remains there (so the second invokation for the same checkbox doesn't insert into the array a second time).
This seems like a ghastly hack to me, but I'll go with it for the time being.