How do I refer to a windows form control by name (C# / VB)
Posted
by Alex
on Stack Overflow
See other posts from Stack Overflow
or by Alex
Published on 2009-07-24T17:17:41Z
Indexed on
2010/05/24
15:01 UTC
Read the original article
Hit count: 220
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()
© Stack Overflow or respective owner