Reputation: 600
I want to populate 40 textblocks on an application, they all have slightly different names but in common they end in a different number.
I would like to use:
for(int i = 1; i < 41; i++)
{
textblock_(i).text = array[i].ToString();
}
Is it possible to do this?
Thanks
Upvotes: 2
Views: 227
Reputation: 8231
In WPF, you can use FindName method.
Firstly, we get an object by FindName(Control's x:Name). And then cast it into your control's type. Just like this:
for (int i = 1; i < 41; i++)
{
TextBlock tb = (this.FindName(string.Format("textblock_{0}", i)) as TextBlock);
tb.Text = array[i].ToString();
}
Upvotes: 2
Reputation: 596
If you are using Windows Forms (WinForms) then: Control.ControlCollection.Find
Example:
TextBox currentTextBox = this.Controls.Find("textBox1" + i.ToString(), true).FirstOrDefault() as TextBox;
currentTextBox.Text = array[i].ToString();
Or in WPF: How can I find WPF controls by name or type? CrimsonX's answer
Upvotes: 0