2017-10-16 48 views
-2

我是一名新的c#程序员,无法更新我的程序添加标签基于文本框的值。如果文本框和标签是使用表单设计器添加的,但它的数量文本框和标签会根据我的用户数据而不同,所以我会使用代码添加它们。不幸的是,在代码中添加的标签在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; 
     } 
    } 
} 
+1

你的标签只有在构造函数存在,因为这是它的声明。您可以在控件集合中找到它(和其他任何人)。 – Plutonix

+0

将您的标签移动到私人领域。 – Arjang

回答

0

移动你的标签是一个私有字段

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; 
     } 
    } 
} 
相关问题