Infinite loop is causing the form to not show up vb - vb.net

I have an infinite loop in this sub because I want the program to keep testing this process to see if the variable has changed. When I run the program in the debugger, nothing shows up, including the form however when I removed the infinite loop from the program, the form showed up again. Does anyone know why this is happening? I should also mention I've tried a DO LOOP as well. Can anyone help?
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim greenCount As Integer
Dim looptest As Boolean = True
While looptest = True
For Each control In Me.Controls.OfType(Of Button)
If control.BackColor = Color.Lime Then
greenCount += 1
End If
Next
txtFielder.Text = greenCount.ToString
End While
End Sub

You need to get rid of all that code regardless. Depending on how you're changing the BackColor of those Buttons in the first place, updating the lime count might be best done there. Otherwise, you should be handling the appropriate event, e.g.
Private limeButtonCount As Integer = 0
Private Sub Buttons_BackColorChanged(sender As Object, e As EventArgs) Handles Button3.BackColorChanged,
Button2.BackColorChanged,
Button1.BackColorChanged
If DirectCast(sender, Button).BackColor = Color.Lime Then
limeButtonCount += 1
Else
limeButtonCount -= 1
End If
TextBox1.Text = limeButtonCount.ToString()
End Sub
Note that this code assumes that there are only two possible BackColor values and that all Buttons are not lime by default. If your scenario is a bit more complex than that then you may need to change a code a little, e.g.
Private limeButtonCount As Integer = 0
Private Sub Buttons_BackColorChanged(sender As Object, e As EventArgs) Handles Button3.BackColorChanged,
Button2.BackColorChanged,
Button1.BackColorChanged
limeButtonCount = Controls.OfType(Of Button)().Count(Function(b) b.BackColor = Color.Lime)
TextBox1.Text = limeButtonCount.ToString()
End Sub

Form.Load occurs before a form is displayed for the first time.
This means that you'll never see your form as long as you loop in this event. You probably want to use the Shown event instead.

Related

How to Remove a control from another Sub than the one where the control was initially created in VB .NET

I have written some code to create a PictureBox every time the code runs, which works fine.
Public Sub BtnHit_Click(sender As Object, e As EventArgs) Handles BtnHit.Click
Dim PicBoxNewCard As New PictureBox
PicBoxNewCard.Width = 114
PicBoxNewCard.Height = 166
PicBoxNewCard.SizeMode = PictureBoxSizeMode.Zoom
DrawCard(PicBoxNewCard)
Me.Controls.Add(PicBoxNewCard)
PicBoxNewCard.Location = New Point((257 + (57 * DrawnCardCounter)), 349)
But I want to be able to delete these created PictureBoxes by pressing a button, which would be in a different sub to the one that creates the Boxes.
I have googled around and have found references to creating Classes, Panels etc and have not had any success. I have found the exact code that I need to make it work, (Me.Controls.Remove(PicBoxNewCard)) but it only seems to work when executed in the same Sub.
Set the Name or Tag property and use that later when searching for the PictureBox to remove.
PicBoxNewCard.Name = $"Card{DrawnCardCounter}"
Private Sub RemoveButton_Click(sender As Object, e As EventArgs) Handles RemoveButton.Click
RemoveCardPicBox(10)
End Sub
Private Sub RemoveCardPicBox(CardNumber As Integer)
Dim delpicBox As PictureBox = Me.Controls.OfType(Of PictureBox).Where(Function(x) x.Name = $"Card{CardNumber}").FirstOrDefault
If Not delpicBox Is Nothing Then
Me.Controls.Remove(delpicBox)
End If
End Sub

Matching cards by using .tag

In this game I am creating, I have a set of "cards" as pictureboxes set to a random lot of images. When the game starts, the images in the pictureboxes are hidden and the user has to guess which image was in each card. I am having trouble with finding if the user's guess matches what was in the actual card.
In the code below, I am using a listbox to score the names of images in which the user can guess from.
https://imgur.com/a/xCg8X
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
If ClickedCard Is Nothing Then 'Make sure that a card has been clicked, otherwise the below code will fail.
MsgBox("You must select a card.")
Return 'Do not continue execution of this code.
End If
btnSubmit.Visible = True
ClickedCard.Image = imglist1.Images(ListBox1.SelectedIndex)
If ClickedCard.Tag = ListBox1.SelectedIndex Then
roundscore += 1
If roundscore = Cards.Count Then
MsgBox("All right")
End If
End If
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Static AlreadySelected As New List(Of Integer)
If AlreadySelected.Contains(ListBox1.SelectedIndex) Then
MessageBox.Show("Already select once")
Exit Sub
End If
AlreadySelected.Add(ListBox1.SelectedIndex)
'Your other code here
End Sub
The static list will persist between calls to this sub. You will have to clear this list when you go to a new round. I hope this helps with the problem you mentioned in your comments. :-)

Threading System.NullReferenceException

I am trying to start and stop a autochecking function when checking or unchecking a checkbox.
Private Sub CheckBoxautorefresh_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBoxautorefresh.CheckedChanged
Dim AutoRefreshThread As Thread = Nothing
If CheckBoxautorefresh.Checked Then
AutoRefreshThread = New Threading.Thread(AddressOf Main.AutoRefresh)
AutoRefreshThread.SetApartmentState(Threading.ApartmentState.STA)
AutoRefreshThread.Start()
Else
AutoRefreshThread.Abort()
End If
End Sub
When I check the Checkbox it starts AutoRefresh-Sub fine, and it works. When I unselect it after that, I get a System.NullReferenceException in this line:
AutoRefreshThread.Abort()
The Autorefresh function just downloads a string every 30 seconds.
And I like to check this autorefresh on/off with a checkbox.
But for some reason it doesn't work.
Can someone help me out? :)
You're defining the thread inside the CheckedChanged event:
Dim AutoRefreshThread As Thread = Nothing
When the checkbox is unchecked, you're referencing a variable that has not actually been instantiated (that only happens when the checkbox is checked). You're no longer referencing the original thread you created when the checkbox was checked.
Try defining AutoRefreshThread outside of the event.
I am not a big fan of .Abort, a lot of gotchas. See http://msdn.microsoft.com/en-us/library/5b50fdsz%28v=vs.110%29.aspx
Try this pattern.
Dim thrd As Threading.Thread
Dim thrdStopped As New Threading.ManualResetEvent(False)
Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
If CheckBox1.Checked Then
If IsNothing(thrd) OrElse thrd.ThreadState <> Threading.ThreadState.Background Then
thrdStopped.Reset() '=false
thrd = New Threading.Thread(AddressOf someThread)
thrd.IsBackground = True
thrd.Start()
End If
ElseIf Not IsNothing(thrd) AndAlso thrd.ThreadState = Threading.ThreadState.Background Then
thrdStopped.Set() '=true
thrd.Join()
End If
End Sub
Private Sub someThread()
Do
Debug.WriteLine(DateTime.Now.ToString("HH:mm:ss.ff"))
Loop While Not thrdStopped.WaitOne(100) 'loop while false, sleep 100 ms.
End Sub

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.

Search ListBox elements in VB.Net

I'm migrating an application from VB6 to VB.Net and I found a change in the behavior of the ListBox and I'm not sure of how to make it equal to VB6.
The problem is this:
In the VB6 app, when the ListBox is focused and I type into it, the list selects the element that matches what I type. e.g. If the list contains a list of countries and I type "ita", "Italy" will be selected in the listbox.
The problem is that with the .Net version of the control if I type "ita" it will select the first element that starts with i, then the first element that starts with "t" and finally the first element that starts with "a".
So, any idea on how to get the original behavior? (I'm thinking in some property that I'm not seeing by some reason or something like that)
I really don't want to write an event handler for this (which btw, wouldn't be trivial).
Thanks a lot!
I shared willw's frustration. This is what I came up with. Add a class called ListBoxTypeAhead to your project and include this code. Then use this class as a control on your form. It traps keyboard input and moves the selected item they way the old VB6 listbox did. You can take out the timer if you wish. It mimics the behavior of keyboard input in Windows explorer.
Public Class ListBoxTypeAhead
Inherits ListBox
Dim Buffer As String
Dim WithEvents Timer1 As New Timer
Private Sub ListBoxTypeAhead_KeyDown(sender As Object, _
e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
Select Case e.KeyCode
Case Keys.A To Keys.Z, Keys.NumPad0 To Keys.NumPad9
e.SuppressKeyPress = True
Buffer &= Chr(e.KeyValue)
Me.SelectedIndex = Me.FindString(Buffer)
Timer1.Start()
Case Else
Timer1.Stop()
Buffer = ""
End Select
End Sub
Private Sub ListBoxTypeAhead_LostFocus(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.LostFocus
Timer1.Stop()
Buffer = ""
End Sub
Public Sub New()
Timer1.Interval = 2000
End Sub
Private Sub Timer1_Tick(sender As Object, e As System.EventArgs) Handles Timer1.Tick
Timer1.Stop()
Buffer = ""
End Sub
End Class
As you probably know, this feature is called 'type ahead,' and it's not built into the Winform ListBox (so you're not missing a property).
You can get the type-ahead functionality on the ListView control if you set its View property to List.
Public Function CheckIfExistInCombo(ByVal objCombo As Object, ByVal TextToFind As String) As Boolean
Dim NumOfItems As Object 'The Number Of Items In ComboBox
Dim IndexNum As Integer 'Index
NumOfItems = objCombo.ListCount
For IndexNum = 0 To NumOfItems - 1
If objCombo.List(IndexNum) = TextToFind Then
CheckIfExistInCombo = True
Exit Function
End If
Next IndexNum
CheckIfExistInCombo = False
End Function