2015-09-21 38 views
1

嗨,我是C#的新手,我想在Form1中將我的textBox1的值顯示在我的Label1中。我試着用這個:如何以另一種形式在標籤中顯示文本框的值?

private void button1_Click(object sender, EventArgs e) 
    { 
     label1.Text = textBox1.Text; 

     Form2 frm = new Form2(); 
     frm.Show(); 
     this.Hide(); 
    } 

但它沒有工作,因爲它是在另一種形式。有人能告訴我怎麼做對嗎?

+0

你有幾個方法可以做到這一點。一,你可以改變'Form2'的構造函數來接受一個字符串。在創建Form2時傳遞'textBox1.Text',然後在構造函數中將值賦給標籤。其他方法是在Form1上設置一個'public'值,它只返回'textBox1.Text'並從'Form2'讀取它,但這樣做更復雜一些,不太好。只是谷歌「如何傳遞形式之間的價值」,這可能會因爲這個重複關閉。 – sab669

+0

你有沒有考慮過創建一個通用靜態類 – Rohit

回答

2

在Form1編寫代碼

private void button1_Click(object sender, EventArgs e) 
{ 
     Form2 form = new Form2(TextBox1.Text); 
     form.Show(); 
    } 

在窗口2寫這

public Form2(string text) 
    { 
     InitializeComponent(); 
     label1.Text = text; 
    } 
+0

form2自動生成&調用構造函數 –

0

嘗試這樣做:

// In Form1.cs. 
private Form2 otherForm = new Form2(); 
private void GetOtherFormTextBox() 
{ 
    textBox1.Text = otherForm.label1.Text; 
} 
private void button1_Click(object sender, EventArgs e) 

    GetOtherFormTextBox(); 
} 
0

另一種選擇

在Form1

private void button1_Click(object sender, EventArgs e) 
{ 
    Form2 frm = new Form2(); 
    frm.LabelText = "My Text"; 
    from.ShowDialog(); 
} 

在表格2

private string labelText; 
public string LabelText { get { return labelText; } set { labelText = value; } } 
private void Form2_Load(object sender, EventArgs e) 
{ 
    label.Text = LabelText; 
} 
相關問題