Referencing a picturebox using a variable image in Visual Basic 2012 - vb.net

I'm trying to modify an answer found here but I'm not having much luck....
What I'm trying to do is:
I have 12 pictures and 12 pictureboxes.
In a loop I'm trying to get it to check for the number and load the corresponding image(s)
so if it's #3 it should load images 1-3 in pictureboxes 1-3
I think I'm close but i can't figure it out
Declaration of Dictionary and passing subroutine
Dim ctrlDict As New Dictionary(Of Image, Control)
Dictionary(ctrlDict)
Definition Sub
Sub dicti(pictures() As Image, ByRef ctrlDict As Dictionary(Of Image, Control))
ctrlDict.Add(pictures(0), PictureBox1)
ctrlDict.Add(pictures(1), PictureBox2)
ctrlDict.Add(pictures(3), PictureBox3)
End Sub
Loop
The error I'm getting is "programname.my.resources is a namespace and cannot be used as an expression" and "picturebox is a type and cannot be used as an expression"
Sub Output(Days() As String, Prices() As String, WhichDay As String, total As Double, ctrlDict As Dictionary(Of Image, Control))
For i As Integer = 0 To 11
If WhichDay >= i Then
ctrlDict(PictureBox & i).Image = pictures(i)
End If
Next
End Sub

Off the top of my head, Pretty sure you cant do
ctrlDict(PictureBox & i).Image = pictures(i)
youll need to find the control that has the name property equal to (PictureBox.name & i). Then use that control and set the image.
Dont have an IDE on this computer but it will be something like
dim controlToUse as PictureBox
for each ctrl in ctrlDict
if ctrl.value.name = "Whatever youre calling your pictureboxes" & i then
controlToUse = ctrl.value
exit for
end if
next
if not controlToUse is nothing then controlToUse.image = pictures(i)
Please note that the above is psuedocode. Do not expect it to compile!

I found the answer
Dim pic As PictureBox
For i As Integer = 0 To 11
If WhichDay >= i Then
pic = Me.Controls("picturebox" & i + 1)
pic.Image = pictures(i)
End If
Next

Related

VBA Userform: Update Total value in a label with multiple inputs, when entries change, by using a class module

I have a userform with 120 textboxes (10 years x 12 months). Going across are the months, and at the end is the total.
This is repeated 10 times for the 10 years going downwards
I would like it so the total label is updated when the values for the corresponding years' months change.
Textboxes are labelled for each year and month. The first one is 'TextBox1_1', the second is 'TextBox1_2'. for the third year, and fifth month it is 'TextBox3_5' and so forth.
I have a module which is set up to calculate the totals:
Sub totalVal(i As Integer)
Dim arr(1 To 12) As Integer
Dim j As Integer
For j = 1 To 12
If Trim(Basic_Info_Setup.Controls("TextBox" & i & "_" & j).Value & vbNullString) = vbNullString Then
Else
arr(j) = Basic_Info_Setup.Controls("TextBox" & i & "_" & j).Value
End If
Next j
Basic_Info_Setup.Year1_Total.Caption = Application.WorksheetFunction.Sum(arr)
End Sub
The 'i' will be passed as the year and the rest can be calculated. However to use this would a change event in all 120 textboxes which is far from ideal, but not undoable.
I have read and understand this is possible with a class module.
This one which shows how to do it with textboxes (Here) and I also had a look at how this one (Here) albeit it confused me more than it helped.
What do I need to do to make this class module for me?
I currently have in the class module, which is called 'clsLabel'
Private WithEvents MyTextBox As MSForms.TextBox
Public Property Set Control(tb As MSForms.TextBox)
Set MyTextBox = tb
End Property
Private Sub MyTextBox_Change()
totalVal (1)
End Sub
and in the userform
Private Sub UserForm_Initialize()
Dim tbCollection As Collection
Dim ctrl As MSForms.Control
Dim obj As clsLabel
Set tbCollection = New Collection
For Each ctrl In Me.Controls
If TypeOf ctrl Is MSForms.TextBoxThen
Set obj = New clsLabel
Set obj.Control = ctrl
tbCollection.Add obj
End If
Next ctrl
Set obj = Nothing
End Sub
when things work I would be happy to change the passing 'i' integer to be dynamic, I just have it set at 1 for now to see if it works for a specific year
There are no errors.
EDIT: corrections to above code as it now works
thanks

Why does Windows.Media.VisualTreeHelper.GetChild(...) exit the sub?

I have a vb application with a listview.
I was testing and ended up with this sub for my dragover event:
Private Sub ListView1_DragOver(sender As Object, e As DragEventArgs) Handles ListView1.DragOver
XToolStripLabel.Text = "X:" & e.X
YToolStripLabel.Text = "Y:" & e.Y
Dim Insertion As Integer = GetInsertion(MousePosition, ListView1)
SelectionTestTSlabel.Text = "SEL " & Insertion
If CurrentlyDragging Then
Dim gr As Graphics = ListView1.CreateGraphics
Windows.Media.VisualTreeHelper.GetChild(New Windows.DependencyObject(), 0) 'I know this seems like it doesn't do much
MsgBox("") 'I actually added this later because the rest of the code did not run normally.
Dim InsertionY As Integer = 24 + (Insertion * TestItemHeight)
If MyLastInsPoint = Insertion Then
Else
ListView1.Refresh()
gr.DrawLine(New Pen(Color.Gray, 3), New Point(0, InsertionY), New Point(ListView1.Width, InsertionY))
End If
MyLastInsPoint = Insertion
End If
End Sub
I realized that the MsgBox("") doesn't popup a message box then i spammed breakpoints on the whole sub.
The sub ran as normal but after this line,
Windows.Media.VisualTreeHelper.GetChild(New Windows.DependencyObject(), 0)
the program returned to the form and did not execute the MsgBox("") line.
What's wrong with the line? The program did not even stop at the End Sub breakpoint.
New Windows.DependencyObject() has no children, so index 0 is not available
See the remaks on MSDN
Call the GetChildrenCount method to determine the total number of
child elements of a parent visual.
The value of reference can
represent either a Visual or Visual3D object, which is why the common
base type DependencyObject is used here as a parameter type.

VB.Net Hangman Game Multiple Rounds

I need some help.
I'm currently creating a Hangman Game in VB.Net.
I'm at the stage where a random word is loaded in from a text file of 6 words, and you can click buttons to guess it. If you guess letters wrong, the frame is shown etc, if they're right, the letter shows in the word through labels.
The next bit, that I'm stuck on, is that multiple rounds are needed. I need there to be 3 turns of this hangman game, so, if you guess the word right you get 10 points, and if you fail, you get 0, And then the game resets with your points and you can play again in Turn 2. Then again in Turn 3, and after Turn 3 finishes, the High Score Form is loaded.
You could create a variable to hold the current round in your Module, at the beginning of each round increase it, and at the end of the round check the current round and make a if then logic.
Dim myRound as Integer = 0
And in the PlayForm in the constructor.
myRound += 1
Once the round is complete.
if myRound >= 3 Then
'open the score page
Else
'start the next round
End if
'In General Declarations:
Dim ButtonList As New List(Of Button) 'or Of Control if you have other types of controls
Dim HgmList As New List(Of PowerPacks.Shape)
Dim AnswerList As New List(Of Label)
'In PlayForm_Load:
With ButtonList
.Clear()
.Add(Me.BtnA)
.Add(Me.BtnB)
.Add(Me.BtnC)
'You get the idea
'Add all your buttons you want to re-enable to the list
End With
With HgmList
.Clear()
.Add(Me.SideFrameLine)
.Add(Me.TopFrameLine)
.Add(Me.CornerFrameLine)
'etc.
End With
With AnswerList
.Add(Me.FirstLetterLbl)
'etc. Just like the other two.
End With
'At the end of your `If Correct = False Then` Block:
Else 'Check for win after each correct guess
Dim Winner As Boolean = True
Dim CheckLetter As Label
For Each CheckLetter in AnswerList
If Not CheckLetter.Visible Then
Winner = False
Exit For
End If
Next
If Winner Then
NextRound(10)
End If
End If
'Somewhere inside your form code:
Private Sub NextRound(RoundScore As Integer)
UserScore += RoundScore
If TurnNumber = 3 Then 'Game Over
MsgBox("Game Over" & vbNewLine & "Score: " & UserScore)
Else 'This is the part you asked about: resetting the form
TurnNumber += 1
PlayForm_Load(Nothing, Nothing)
Dim ResetControl As Control
Dim ResetShape As PowerPacks.Shape
For Each ResetControl In ButtonList
ResetControl.Enabled = True
Next
For Each ResetShape In HgmList
ResetControl.Visible = False
Next
End If
End Sub
I only added the .Clear() to the list builders because you already have your code to get a new word in PlayForm_Load. If you move it (say to a new Sub called NewWord), you don't need .Clear, and you would call your new sub instead of PlayForm_Load.

Binary Search or Insertion Sort with list view [Visual Basic .net]

Recently when creating a program for my client as part of my computing project in visual basic .net I've came across a problem, which looks like following; In order to receive additional marks for my program I must take an advantage of either Binary Search or Insertion Sort subroutine declared recursively, so far the only place I can use it on is my View form which displays all reports generated by program but the problem with this is since I'm using MS Access to store my data all of the data is downloaded and placed in listview in load part of form. So the only way I can use it is by running it on listview which is a major problem for me due to the fact that I'm not very experienced in vb.
For binary search I have tried downloading all of the items in specified by user column into an array but that's the bit I was struggling on the most because I'm unable to download all items from only one column into an array. Also instead of searching every single column user specifies in my form in which column item is located (For example "19/02/2013" In Column "Date"), In my opinion if I manage to download every single entry in specified column into an array it should allow me to run binary search later on therefore completing the algorithm. Here's what I've got so far.
Sub BinarySearch(ByVal Key As String, ByVal lowindex As String, ByVal highindex As String, ByVal temp() As String)
Dim midpoint As Integer
If lowindex > highindex Then
MsgBox("Search Failed")
Else
midpoint = (highindex + lowindex) / 2
If temp(midpoint) = Key Then
MsgBox("found at location " & midpoint)
ElseIf Key < temp(midpoint) Then
Call BinarySearch(Key, lowindex, midpoint, temp)
ElseIf Key > temp(midpoint) Then
Call BinarySearch(Key, midpoint, highindex, temp)
End If
End If
End Sub
Private Sub btnSearch_Click(sender As System.Object, e As System.EventArgs) Handles btnSearch.Click
Dim Key As String = txtSearch.Text
Dim TargetColumn As String = Me.lstOutput.Columns(cmbColumns.Text).Index
Dim lowindex As Integer = 0
Dim highindex As Integer = lstOutput.Items.Count - 1
'Somehow all of the items in Target column must be placed in temp array
Dim temp(Me.lstOutput.Items.Count - 1) As String
' BinarySearch(Key, lowindex, highindex, temp)
End Sub
For Insertion sort i don't even have a clue how to start, and the thing is that I have to use my own subroutine instead of calling system libraries which will do it for me.
Code which I have to use looks like following:
Private Sub InsertionSort()
Dim First As Integer = 1
Dim Last As Integer = Me.lstOutput.
Dim CurrentPtr, CurrentValue, Ptr As Integer
For CurrentPtr = First + 1 To Last
CurrentValue = A(CurrentPtr)
Ptr = CurrentPtr - 1
While A(Ptr) > CurrentValue And Ptr > 0
A(Ptr + 1) = A(Ptr)
Ptr -= 1
End While
A(Ptr + 1) = CurrentValue
Next
Timer1.Enabled = False
lblTime.Text = tick.ToString
End Sub
Any ideas on how to implement this code will be very appreciated, and please keep in my mind that I'm not very experienced in this language
Perhaps this might give you a place to begin. If you already have a ListView with "stuff" in it you could add a button to the form with the following code to copy the Text property for each item into an array:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim myArray(Me.ListView1.Items.Count - 1) As String
Dim i As Integer
' load array
For i = 0 To Me.ListView1.Items.Count - 1
myArray(i) = Me.ListView1.Items(i).Text
Next
' show the results
Dim s As String = ""
For i = 0 To UBound(myArray)
s &= String.Format("myArray({0}): {1}", i, myArray(i)) & vbCrLf
Next
MsgBox(s, MsgBoxStyle.Information, "myArray Contents")
' now go ahead and manipulate the array as needed
' ...
End Sub

What's the best way to create a drop-down list in a Windows application using Visual Basic?

I'd like to add a drop-down list to a Windows application. It will have two choices, neither of which are editable. What's the best control to use? Is it a combo box with the editing property set to No?
I'm using Visual Studio 2008.
I'd suggest taking a look at the Windows Vista User Experience Guide. It sounds like you might be better off with radio buttons, or, if it's an explicit on/off type of situation, using a check box. I think we'd really need more info, though.
yourComboBox.DropDownStyle = ComboBoxStyle.DropDownList
Set the DropDownStyle property to DropDownList.
See http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.dropdownstyle(VS.80).aspx
The combobox in winforms doubles as a uneditable drop down list by changing the DropDownStyle property to "DropDownList": I don't think there is a separate drop down list control.
Create two text boxes next to each other TextBox1 and TextBox2, for TextBox2 set multiple lines and autosize.
create your dropdown list somewhere. In my example it was in a different sheet with about 13,000 entries.
Below are two functions, the first drives the input box, TextBox1. as you type, the 2nd box, TextBox2 shows the remaining valid choices. The second function, loads the first textbox if you click on a choice in the second box
In the below, cell B3 on the current sheet had to be loaded with the typed/selected answer. In my application, I only wanted to search for uppercase characters hence the UCase usage. My list data was 13302 entries in column Z
Private Sub TextBox1_Keyup(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Dim curtext As String
Dim k, where As Integer
Dim tmp As String
Dim bigtmp As String
curtext = TextBox1.Text
curtext = UCase(curtext)
TextBox1.Text = curtext
Range("b3").Value = curtext
If Len(curtext) = 0 Then
TextBox2.Visible = False
Exit Sub
End If
TextBox2.Visible = True
Application.ScreenUpdating = False
For k = 2 To 13303 ' YOUR LIST ROWS
tmp = Sheets("General Lookup").Range("Z" & k).Value ' YOUR LIST RANGE
where = InStr(1, tmp, TextBox1.Text, 1)
If where = 1 Then
bigtmp = bigtmp & tmp & Chr(13)
End If
Next
TextBox2.Text = bigtmp
Application.ScreenUpdating = True
End Sub
Private Sub TextBox2_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
If Len(TextBox2.SelText) > 0 Then
TextBox1.Text = TextBox2.SelText
Range("b3").Value = TextBox2.SelText
TextBox2.Visible = False
End If
End Sub