First of all, you have made a mistake in first place by creating so many text boxes using the designer. You should understand that the designer is for simple ad-hoc totally manual "programming"; if you need some repeating pattern like 10 text boxes, adding them all is a manual monkey job.
Now, about the
IEmumerable
. First of all, you need to use only the generic interface
System.Collections.Generic.IEnumerable<T>
:
http://msdn.microsoft.com/en-us/library/9eekhta0.aspx[
^].
What to use for
T
? Let's assume you have something which provides the text for all your text boxes. This "something" shall also have the property
Text
:
interface ITextProvider {
string Text { get; set; }
}
class MyTextProvider : SomeBaseClass, ITextProvider {
string ITextProvider.Text { get { return text; } set { text = value; } }
string text;
}
IEnumerable<ITextProvider> textPopulator =
Now, how to work with text boxes?
There are two solutions. First one is dumb, in the case you don't want to fix your (really bad) designer-made mistake. Here is the work-around:
TextBox[] textBoxes = new TextBox[] { txtSomething_1, txtSomething_2, };
Even the names of those text boxes are unacceptable, violate (good) Microsoft naming conventions. Yes, the designer violates them. You always should rename all the auto-generated names to something semantic. But in this case, you should not use the designer. OK, later about it; now, let's see how to populate it. It's trivial:
int index = 0;
foreach(ITextProvider textProvider in textPopulator) {
if (textBoxes.Length < index + 1) break;
textBox[index].Text = textProvider.Text;
++index;
}
Now, if you really want to write correct code, you should create your text boxes properly in first place. Let's assume you put them in some container control like a panel:
Control parent = SomePanel;
int left =
int verticalGap =
int count = textPopulator.Length;
TextBox[] textBoxes = new TextBox[count];
for (int index; index < count; ++index) {
TextBox textBox = new TextBox();
textBox.Text = textPopulator[index].Text;
textBox.Left = left;
textBox.Top = index * (textBox.Height + gap);
textBox.Parent = parent;
textBoxes[index] = textBox;
}
Something like this.
—SA