VS 2010 VB Find Control on Form

喜欢而已 提交于 2020-02-08 05:21:05

问题


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"


来源:https://stackoverflow.com/questions/43101383/vs-2010-vb-find-control-on-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!