-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;
}
}
}
你的標籤只有在構造函數存在,因爲這是它的聲明。您可以在控件集合中找到它(和其他任何人)。 – Plutonix
將您的標籤移動到私人領域。 – Arjang