如何在c# winform中从父窗体传递数据到子窗体



我试图通过一些字符串(设备信息)从父形式(主要形式)在MDI的子形式

  • 子窗体显示
  1. 设备名称
  2. 设备型号
  3. 生产日期,
  • 当点击父表单中的ON按钮时,所有这些特性都应该传递给子表单。
  • 子表单通过菜单调用。
  • 到目前为止,我只成功地通过菜单调用了子进程,但无法传递数据。

父窗体:菜单,以便在MDI(父窗体)上查看子窗体。

private void DeviceInfomationToolStripMenuItem_Click(object sender, EventArgs e)
{
if (Application.OpenForms["Child"] is Child deviceInfo)
{
deviceInfo.Focus();
return;
}
deviceInfo = new Child();
deviceInfo.MdiParent = this;
deviceInfo.Show();
}

Parent From: On button event

private void btnOn_Click(object sender, EventArgs e)
{
deviceName = "Notebook520220624";
deviceModel =  "520220627";
manuFacturedDate = "220627";
Child form = new Child(deviceName);
}

子窗体:接收设备信息并显示它

public Child(string deviceName)
{
InitializeComponent();
name_lbl.Text = deviceName
//name_lbl.Text = deviceName.ToString();
//model_lbl.Text = diviceModel;
//date_lbl.Text = manuFacturedDate;
}

您可以在方法外部的父窗体中声明静态变量,在类级全局作用域中,然后通过子窗体构造函数中的类型访问该变量,因此,例如

public static string deviceName = ""; // Here I declared static string global variable, and initialized to empty string
private void btnOn_Click(object sender, EventArgs e)
{
deviceName = "Notebook520220624"; // Assign the value to variable
deviceModel =  "520220627";
manuFacturedDate = "220627";
}

然后,在子窗体中,您可以通过调用this

,通过默认构造函数将静态变量的值传递给文本框
public Child()
{
InitializeComponent();
name_lbl.Text = ParentForm.deviceName; // Here I put name ParentForm type name regarding to this example, but you should change according to your name of your class
}

可以创建两个构造函数。当创建子表单时,您可以提供任何数据,也可以不提供。

public Child(string deviceName)
{
InitializeComponent();
name_lbl.Text = deviceName  
}
public Child()
{
InitializeComponent();  
}

最新更新