How do I refer to a windows form control by name (C# / VB)

前端 未结 6 414
情话喂你
情话喂你 2020-12-21 08:21

Suppose I have a label control on a windows form called \"UserName\". How can I refer to that label programmatically using the label name?

For example I can do:

相关标签:
6条回答
  • 2020-12-21 08:26

    You should be able to use Find():

    TabPage.Controls.Find("UserName", false);
    

    This will search all of the child controls and return an array of those that match the string. If you specify true for the 2nd argument, it will look through the controls of the child controls as well.

    0 讨论(0)
  • 2020-12-21 08:26

    Is your control added at design time or runtime?

    If it is added at design time then you can simply reference it by name: Me.UserName.Text = "Something"

    If it is added at runtime you can use the following:

    TabPage.Controls.Find("UserName", true) 
    

    The second parameter tells it to search all children as well, so this should definitely find your control.

    0 讨论(0)
  • 2020-12-21 08:41

    How are you creating your controls?

    If it's at design time, then each control should have a named reference.

    If you're adding controls at run time, then you could create a dictionary to contain references indexed by string and add each control to that dictionary when it's created.

    0 讨论(0)
  • 2020-12-21 08:43

    One solution would be to pass the controls to the class in addition to or instead of the tabpage. For example, you could have a RecordCounter property in addition to your ActivePage property. (Incidentally, Find is efficient to code but not so efficient at runtime.)

    0 讨论(0)
  • 2020-12-21 08:45

    TabPage.Controls.Find("UserName", true) works for me. But i need to assign it to controls[] class and next i am assigning it to textbox like controls.

    0 讨论(0)
  • 2020-12-21 08:50

    Unless I'm misunderstanding the question context, I think you're making it too difficult. in code, you just use thelabel name as your reference as in:

    UserName.Text = "Something"
    

    Is there something you're trying to accomplish that makes that not right?

    0 讨论(0)
提交回复
热议问题