多界面参数传递
需要在多个界面之间相互传递参数,对方法做记录与实例,以便回顾。
重写构造函数
父窗体:
private void ToolStripMenuItem1_Click(object sender, EventArgs e)
{
globalparam.ItermPath = "string";
DeviceConnectForm DeviceConnect = new DeviceConnectForm(globalparam.ItermPath);
DeviceConnect.ShowDialog();//模态
}
重载子窗体的构造函数
public partial class Form2 : Form
{
public DeviceConnectForm(string ItermPath)//修改构造函数,增加一个字符串形参
{
InitializeComponent();
CB_SourceAddr.Text = ItermPath; //界面显示
}
}
缺点:父窗体向子窗体传递,只能传递一个参数,不能子窗体向父窗体传递。
通过子窗体私有变量传递
父窗体:
//传递变量到子窗口
private void btn_Input_BtnClick(object sender, EventArgs e)
{
childForm childForm = new childForm();//childForm为新建窗口类
childForm.str = this.tb_MainFormIn.InputText ;//str为子类的公有变量
if (childForm.ShowDialog() == DialogResult.OK) return;
}
子窗体:
namespace demo_Params
{
public partial class childForm : Form
{
public childForm()
{
InitializeComponent();
}
//私有变量和赋值,value值在父窗口传递
public string ItermPath;
public string str
{
set
{
ItermPath= value;
}
}
//显示父窗口的变量到文本框
private void btn_getPara_BtnClick(object sender, EventArgs e)
{
this.tb_childFormIn.Text = ItermPath;
}
}
}
PS:方向为父窗体向子窗体传递
事件委托
通过委托事件和事件触发执行函数来解决参数的传递和接收。
父窗体:
namespace WindowsFormsApp1
{
public partial class MainPage : System.Windows.Forms.Form
{
public MainPage()
{
InitializeComponent();
}
private void 新建ToolStripMenuItem_Click(object sender, EventArgs e)
{
NewIterm newIterm = new NewIterm();
newIterm.getParam += new backParam(GetChildParam);//绑定事件
newIterm.ShowDialog();
}
//委托事件执行方法
void GetChildParam(string ItermPath)
{
globalparam.ItermPath = ItermPath;
}
}
}
子窗体:
namespace NewItermForm
{
public delegate void backParam(string str);//声明委托
public partial class NewIterm : Form
{
public struct Globalparam
{
public bool isDragging;
public Point dragOffset;
public String ItermPath;
};
public string str;
//实例化结构体
public Globalparam globalparam = new Globalparam();
public event backParam getParam;//委托事件,接受一个string变量
public NewIterm()
{
InitializeComponent();
}
private void NewIterm_Load(object sender, EventArgs e)
{
globalparam.ItermPath = SaveFile();
}
private void Btn_Exit_Click(object sender, EventArgs e)
{
this.Close();
getParam(globalparam.ItermPath);//委托
}
}
}