C# 基于文本框值以编程方式更新添加的标签

C# 基于文本框值以编程方式更新添加的标签,c#,C#,我是一名新的c#程序员,无法根据textbox值以编程方式更新添加的标签。如果使用表单设计器添加文本框和标签,效果很好,但是文本框和标签的数量会根据用户的数据而变化,因此我将使用代码添加它们。不幸的是,代码中添加的标签在Text_Changed事件中无法访问,我在互联网上的搜索也没有明确说明如何实现这一点。下面是我的代码 namespace Test_Form_Controls { public partial class Form1 : Form { publi

我是一名新的c#程序员,无法根据textbox值以编程方式更新添加的标签。如果使用表单设计器添加文本框和标签,效果很好,但是文本框和标签的数量会根据用户的数据而变化,因此我将使用代码添加它们。不幸的是,代码中添加的标签在Text_Changed事件中无法访问,我在互联网上的搜索也没有明确说明如何实现这一点。下面是我的代码

namespace Test_Form_Controls
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            TextBox txtBox1 = new TextBox();
            txtBox1.Text = "0";
            txtBox1.Location = new Point(100, 25);
            Controls.Add(txtBox1);
            txtBox1.TextChanged += txtBox1_TextChanged;
            Label label1 = new Label();
            label1.Text = "0";
            label1.Location = new Point(25, 25);
            Controls.Add(label1);
        }

        private void txtBox1_TextChanged(object sender, EventArgs e)
        {
            TextBox objTextBox = (TextBox)sender;
            label1.Text = objTextBox.Text;
        }
    }
}

将标签移动到专用字段

namespace Test_Form_Controls
{
    public partial class Form1 : Form
    {
        Label label1;
        public Form1()
        {
            InitializeComponent();
            TextBox txtBox1 = new TextBox();
            txtBox1.Text = "0";
            txtBox1.Location = new Point(100, 25);
            Controls.Add(txtBox1);
            txtBox1.TextChanged += txtBox1_TextChanged;
            label1 = new Label();
            label1.Text = "0";
            label1.Location = new Point(25, 25);
            Controls.Add(label1);
        }

        private void txtBox1_TextChanged(object sender, EventArgs e)
        {
            TextBox objTextBox = (TextBox)sender;
            label1.Text = objTextBox.Text;
        }
    }
}

您的标签只存在于ctor中,因为它是在ctor中声明的。您可以在控件集合中找到它(以及任何其他控件)。请将标签移动到专用字段。