Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

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

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:

For each ctrl as Control in TabPage.Controls
If ctrl.Name = "UserName" Then
' Do something
End If
Next

This seems quite inefficient. I would like to do something like:

TabPage.Controls("UserName").Text = "Something"

I did some googling but couldn't find a satisfactory answer. Most suggested looping, some said .NET 2005 doesn't support direct refenece using string name, and FindControl method was asp.net only...

EDIT

Thanks for the response so far. Here is a bit more detail.

I have a windows form with three tabpages, all of which a very similar in design and function i.e. same drop down menus, labels, react in simlar way to events etc.

Rather than write code for each event per tabpage I have built a class that controls the events etc. per tabpage.

For example, on each tabpage there is a Label called "RecordCounter" that simply shows the number of rows in the datagridview when it is populated by selection of a variable in a drop down menu.

So what I want to be able to do is, upon selection of a variable in the drop down menu, the datagridview populates itself with data, and then I simply want to display the number of rows in a label ("RecordCounter").

This is exactly the same process on each tabpage so what I am doing is passing the tabpage to the class and then I want to be able to refer to the "RecordCounter" and then update it.

In my class I set the ActivePage property to be the TabPage that the user has selected and then want to be able to do something like:

ActivePage.RecordCounter.Text = GetNumberOfRows()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...