I'm trying to create a window form app with arround 20 textboxes, named "TB1", "TB2",.... The problems is, if I have to work with 20 individual textbox, it might be really annoying. Is there any way to create a list like: TB[], then assign TB1 to TB[0], TB2 to TB[1],...?
Thank you.
CodePudding user response:
They're already in a list; they have to be added to a ControlCollection in order to even show up on a form
this.Controls.OfType<TextBox>().Where(tb => tb.Name.StartsWith("TB"))
will, for example, give you them (it picks on all textboxes directly on the form, with a name that starts TB. If you have other textboxes also called TBx that you don't want in this, then pick in another property that identifies the ones you do want, or e.g. rename the controls you're interested in so you can pick them up by a pattern in the name)
You could put this in a class level list, in the constructor:
class YourForm: Form{
private List<TextBox> _tbList;
YourForm(){
InitializeComponent();
tbList = Controls.OfType<TextBox>().Where(tb => tb.Name.StartsWith("TB")).ToList();
}
}
And then you could do things like clearing all of them:
_tbList.ForEach(tb => tb.Clear());
List is used to give access to ForEach; it's a List thing, not a LINQ thing - normal arrays don't have ForEach. If you use an array rather than a list you'd need to write eg foreach(var tb in _tbArray) tb.Clear();
but it's the same overall effect
Note, if your textboxes are in panels or group boxes, they won't be in this.Controls
they will be in thePanel.Controls
Note2, if the order matters then you can sort strings of TB1, TB2 .. TB9, TB10, ... correctly with:
Controls.OfType<TextBox>()
.Where(tb => tb.Name.StartsWith("TB"))
.OrderBy(tb => (tb.Name.Length, tb.Name))
CodePudding user response:
An alternative to using the controls collection. The trick is hooking them all up to one event handler:
private TextBox[] TB = new TextBox[19];
public void Form_Load(object sender, EventArgs e){
for (int i = 0 ; i < 20; i )
{
TB[i].Name = "TB" i.ToString();
// Set Location, Visible & Text
TB[i].Changed = TextBox_Changed;
}
}
private void TextBox_Changed(object sender, EventArgs e)
{
TextBox txt = sender as TextBox;
int i = Convert.ToInt32(txt.Name.Replace("TB", string.Empty));
Console.Write(TB[i].Text " has changed");
}