進入VS2005後,大家可以發現子表單操作父表單不能沿用2003下的方法:把父表單的空間訪問屬性由private改為public.IDE已經把控制項聲明這部分程式碼後置了,所以只有採用更加對象一點的方法。
父表單與子表單間的參數傳遞我採用的步驟如下:
1 父表單中聲明一個靜態父表單類型的臨時對象
public static frmFather frmFatherTemp;
2 父表單建構函式中對該變數賦值
public frmFather()
{
InitializeComponent();
frmFatherTemp = this;
}
3 把要傳遞的參數設定為父表單的一個屬性,並設定訪問器。訪問其的set方法中進行了參數與父表單控制項綁定的操作。
private string testValue;
public string TestValue
{
get
{
return testValue;
}
set
{
this.testValue = value;
this.txtFather.Text = value;
}
}
4 父表單參數傳遞事件中對要傳遞的參數賦值,並開啟子表單。父表單的工作到此結束。
this.TestValue = this.txtFather.Text;
frmSon frm = new frmSon();
frm.ShowDialog();
5 子表單建構函式中設定傳遞參數與子表單控制項的綁定操作
public frmSon()
{
InitializeComponent();
this.txtSon.Text = frmFather.frmFatherTemp.TestValue;
}
6 子表單回傳事件中,對父表單的臨時對象的該參數屬性賦值
public frmSon()
{
InitializeComponent();
this.txtSon.Text = frmFather.frmFatherTemp.TestValue;
}
ok。一切搞定!
全部代碼如下:
frmFather.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace winFormParameterPass
{
public partial class frmFather : Form
{
public static frmFather frmFatherTemp;
private string testValue;
public string TestValue
{
get
{
return testValue;
}
set
{
this.testValue = value;
this.txtFather.Text = value;
}
}
public frmFather()
{
InitializeComponent();
frmFatherTemp = this;
}
private void btnFather_Click(object sender, EventArgs e)
{
this.TestValue = this.txtFather.Text;
frmSon frm = new frmSon();
frm.ShowDialog();
}
}
}
frmSon.csusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace winFormParameterPass
{
public partial class frmSon : Form
{
public frmSon()
{
InitializeComponent();
this.txtSon.Text = frmFather.frmFatherTemp.TestValue;
}
private void btnSon_Click(object sender, EventArgs e)
{
frmFather.frmFatherTemp.TestValue = this.txtSon.Text;
this.Close();
}
}
}
例子程式:
/Files/heekui/winFormParameterPass.rar
以上想法給新手們一點參考,請高手指教。