Reputation: 2341
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?
}
Upvotes: 0
Views: 4659
Reputation: 460228
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 use LINQ
to find the relevant TextBoxes
:
var myTextBoxes = myPanel.Controls.OfType<TextBox>();
Enumerable.OfType
will filter and cast the controls accordingly. If you want to filter them more, you could use Enumerable.Where
, for example:
var myTextBoxes = myPanel.Controls
.OfType<TextBox>()
.Where(txt => txt.Name.ToLower().StartsWith("e"));
Now you can iterate those TextBoxes
, for example:
foreach(TextBox txt in myTextBoxes)
{
String text = txt.Text;
// do something amazing
}
Edit:
The TextBoxes are on multiple TabPages. Also, the names are a little more logical ...
This approach works also when the controls are on multiple tabpages, for example:
var myTextBoxes = from tp in tabControl1.TabPages.Cast<TabPage>()
from panel in tp.Controls.OfType<Panel>()
where panel.Name.StartsWith("TextBoxGroup")
from txt in panel.Controls.OfType<TextBox>()
where txt.Name.StartsWith("e")
select txt;
(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
).
Upvotes: 2
Reputation: 12137
Try this :
this.Controls.Find()
for(int i= 0; i < 4; ++i) {
string name = "e" + i;
TextBox txtBox = this.Controls.Find(name) as TextBox;
}
Or this :
this.Controls["name"]
for(int i= 0; i < 4; ++i) {
string name = "e" + i;
TextBox txtBox = this.Controls[name] as TextBox;
}
Upvotes: 0
Reputation: 1563
You can use parent of your controls like this(Assuming you have placed all controls in the form, so I have used this)
for(int i= 0; i < 4; ++i) {
string name = "e" + i;
TextBox txtBox=this.Controls[name] as TextBox;
Console.Writeline(txtBox.Text);
}
Upvotes: 2