Reputation: 37
So I have 10 textboxes called TextBox1
-> TextBox10
Is it possible to write a for loop, create a string TextBox + i
and use that String to set the text of the textboxes?
Upvotes: 0
Views: 436
Reputation: 505
As @npap mentioned you can use FrameworkElement.FindName(string)
.
Somewhere in xaml:
<StackPanel>
<TextBox Name="Textbox1"/>
<TextBox Name="Textbox2"/>
<TextBox Name="Textbox3"/>
<TextBox Name="Textbox4"/>
<TextBox Name="Textbox5"/>
<TextBox Name="Textbox6"/>
<TextBox Name="Textbox7"/>
<TextBox Name="Textbox8"/>
<TextBox Name="Textbox9"/>
<TextBox Name="Textbox10"/>
</StackPanel>
Code behind:
using System.Windows;
using System.Windows.Controls;
namespace YourWpfApp
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
LoopOverTextBoxes();
}
private void LoopOverTextBoxes()
{
for (int i = 1; i <= 10; i++)
{
var textbox = (TextBox)FindName($"Textbox{i}");
textbox.Text = $"Name of this textbox is {textbox.Name}";
}
}
}
}
Upvotes: 1