天天看點

[C#] winform 子窗體向父窗體傳值

父窗框mainForm;子窗體childForm,利用事件進行傳值

在子窗體中的操作:

public event EventHandler accept;
public string value;

 private void btnStart_Click(object sender, EventArgs e)
 {

  value=txtName.text;

  if(accept!=null)

   {

    accept(this, EventArgs.Empty);//當事件觸發時,傳遞自身引用

   }

 }
      

在父窗體中的操作:

childForm frmChild=new childForm();

private void btnForm_Click(object sender, EventArgs e)
 {

  if(frmChild.IsDisposed)

  {

    frmChild=new childForm();//時刻保持隻有一個窗體顯示

  }

  frmChild.accept += new EventHandler(Main_accept);
      frmChild.Show();

}

//父窗體處理子窗體傳來的值

public void Main_accept(object sender, EventArgs e)
{
            childForm frmChild= (childForm)sender;
            string childValue = childForm .value;

    txtUser.text=childValue;
 }