2013-09-21 70 views

回答

3

如何讓Form1讀取Form2中的文本字段?

想必Form1產生的Form2實例...所以堅持這種實例,並在窗體上公開相應的屬性:

Form2 form2 = new Form2(); 
form2.Show(); // Or ShowDialog? 

string name = form2.UserName; 

UserName的實施很可能只是獲取從價值文本字段:

public string UserName { get { return userNameTextField.Text; } } 

可以直接與財產公開文本字段,但我個人傾向於認爲表單應該「擁有」其UI,並且不要讓其他代碼混淆它。

0

您可以創建方法和Form1以從textfields

public string GetTextFieldText() 
{ 
    return textfield.Text; 
} 

retreive數據或與財產包起來

public string TextField 
{ 
    get 
    { 
     return textfield.Text; 
    } 
} 

然後從窗口2這樣的訪問:

Form1 frm1 = new Form1(); 
string text = frm1.TextField; // Or GetTextFieldText() 
0

用修飾符public創建全局變量,然後使用Text_Changed事件或button_click事件(如果要在按鈕單擊後檢索文本,請將文本框的文本分配給變量。

然後在您的Form1。你在你的form2和使用

Form2 form = new Form2(); 
    //Then do whatever u want with the variable 
    MessageBox.Show(form.globalVariableName); 

設置文本框的修改屬性publicForm1

Form2 form = new Form2(); 
    //Then do whatever u want with the textbox 
    MessageBox.Show(form.TextBoxName.Text); 
0

這應該讓你開始:

//Global Variable 
Form2 frm2; 

//assuming form1 is the creator of form2 
public Form1() 
{ 
    frm2 = new Form2(); 
} 

//in your Form1, under read data button for example: 
string myName = frm2.TextBox1.Text;