2017-07-02 29 views
2

在窗體1中,單擊「添加」後將彈出窗體2。單擊「確定」按鈕後,如何關閉當前窗體並將字符串傳遞給預製件

private void btAdd_Click(object sender, EventArgs e) 
    { 
     DialogResult dr = new DialogResult(); 

     AddWinForm addWinForm = new AddWinForm(); 

     dr = addWinForm.ShowDialog(); 
     addWinForm.Show(); 
    } 

我想要的是,它將傳遞輸入字符串並刷新Form1中的列表框並單擊「確定」按鈕後關閉Form2。但它看起來有些不妥。

private void btnOK_Click(object sender, EventArgs e) 
    { 
     MainForm mainForm = new MainForm(); 
     mainForm.AddMessageInfo = textBoxAddWinForm.Text; 
     mainForm.Close(); 
    } 

回答

2

您需要讓Form1知道用戶按下了OK按鈕。

Form1中:

private void btAdd_Click(object sender, EventArgs e) 
{ 
    AddWinForm addWinForm = new AddWinForm(); 
    DialogResult dr = addWinForm.ShowDialog(); 

    if(dr == DialogResult.OK) 
    { 
     string info = addWinForm.AddMessageInfo; 

     // do something 
    } 
} 

窗體2:

public string AddMessageInfo { get; private set; } 

private void btnOK_Click(object sender, EventArgs e) 
{ 
    AddMessageInfo = textBoxAddWinForm.Text; // Set AddMessageInfo 
    this.DialogResult = DialogResult.OK; // Let parent form know you pressed OK 
    this.Close(); // Close this form 
} 
0

這不是優雅的方式做,但它能夠完成任務。 其他方法是你可以使用代表將信息從一種形式傳遞給另一種形式。

Public class addWinForm : Form 
    { 
    ... 
     public string Answer { get { return answer;}} 
     private string answer; 

     private void btnOK_Click(object sender, EventArgs e) 
     { 
      //this is supposed 
      answer = "1111"; 
      Close(); 
     } 
    } 
public class MainForm : Form 
{ 
    .... 
    private AddWinForm addWinForm = null;  
    private void btAdd_Click(object sender, EventArgs e) 
     {  
      addWinForm = new AddWinForm(); 

      addWinForm.ShowDialog(); 
      string answerAfterButtonOk = addWinForm.Answer; 
      addWinForm.Dispose(); 
      addWinForm = null; 
     } 
} 
相關問題