简体   繁体   中英

C# WPF using string to access TextBox

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?

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}";
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM