I have a few different TextBox elements named as followed "e0", "e1", "e2", "e3". I know how many there are and I just want to be able to loop through them and grab their values rather than typing each one out manually.
I'm assuming I'll be doing something like this, I just don't know how to access the element.
for(int i= 0; i < 4; ++i) {
string name = "e" + i;
// How do I use my newly formed textbox name to access the textbox
// element in winforms?
}
I would advise against this approach since it's prone to errors. What if you want to rename them, what if you'll forget about this and add other controls with name
e...
?Instead i would collect them in a container control like
Panel
. Then you can useLINQ
to find the relevantTextBoxes
:Enumerable.OfType
will filter and cast the controls accordingly. If you want to filter them more, you could useEnumerable.Where
, for example:Now you can iterate those
TextBoxes
, for example:Edit:
This approach works also when the controls are on multiple tabpages, for example:
(note that i've added another condition that the panels names' must start with
TextBoxGroup
, just to show that you can also combine the conditions)Of course the way to detect the relevant controls can be changed as desired(f.e. with
RegularExpression
).Try this :
Or this :
You can use parent of your controls like this(Assuming you have placed all controls in the form, so I have used this)