VS 2010 VB Find Control on Form

2019-09-14 07:28发布

问题:

My daughter has school homework and is making a snakes and ladders game and she has created a 7 x 7 grid with labels. When she wants to set the position of the player she has multiple if statements and I knew there was a quicker and more efficient way. But it has been years since I played with VS2010

Basically I thought should could do something like this

Form.FindControl("Label"+player1position).Text = "x"

instead of doing

if player1position = 1 then
   label1.text = "x"
end if
if player1position = 2 then
   label2.text = "x"
end if

and so on.

回答1:

Sure, assuming WinForms, you can do something like:

Dim matches() As Control = Me.Controls.Find("Label" + player1position, True)
If matches.Length > 0 AndAlso TypeOf matches(0) Is Label Then
    Dim lbl As Label = DirectCast(matches(0), Label)
    lbl.Text = "x"
End If

The above snippet will find the Label no matter how deeply nested it is, and also will find them if they are in different containers.

If the Labels are all in the same container, then you can shorten it to something like:

Me.Controls("Label" + player1position).Text = "x"

That would find the Label if it is directly on the Form. For a different container, replace "Me" with the name, such as "Panel1":

Panel1.Controls("Label" + player1position).Text = "x"