I'm trying to make a minesweeper game as a project in vb but I can't figure this bit out, any help is appreciated.
I have a grid of 100 pictureboxes on a form, and then code to randomly choose several places in an 10x10 array to mark as "bomb" (as a string at the minute). My problem is that I don't know how to relate the box that was clicked to it's place in the array.
I know how to use DirectCast, but have not been able to implement that in this case. I had also thought about trying to use the pictureboxes as objects, but am not sure how that works.
Hopefully someone can help!
One way would be to embed the position in the Name property of each PB (then parse it in the click handler).
Parsing in the click handler sounds like a good idea. How would I go about doing this? Sorry, I have little experience.
You could simply name all of the PictureBoxes with the same prefix, then the row and column; with those three parts separated with an underscore. For instance, the PictureBox in row 2, column 3, could be named "pb_2_3".
Now you can use a common handler and String.Split()
to retrieve the row/column:
Private Sub pbs_Click(sender As Object, e As EventArgs) Handles pb_2_3.Click, pb_2_4.Click
Dim pb As PictureBox = DirectCast(sender, PictureBox)
If pb.Name.ToLower.StartsWith("pb_") Then
Dim values() As String = pb.Name.Split("_")
If values.Length = 3 Then
Dim row As Integer = CInt(values(1))
Dim col As Integer = CInt(values(2))
Debug.Print(String.Format("Name: {0}, Row: {1}, Col: {2}", pb.Name, row, col))
End If
End If
End Sub
Obviously this means you'll have to rename all 100 of your PictureBoxes by hand...not fun; but you'd also have to do that if you used the Tag() property approach as well.