I am trying to pass some strings(device info) from the parent form(the main form )in MDI to the child form
- The child form displays
- Device name
- Device model number
- Manufactured date,
- All these features should be passed to the child form when the ON button in the parent form is being clicked.
- The child form is called through the menu.
- Till now I have had success in only calling the child through the menu but cannot pass the data.
Parent Form: menu to view the child form on the MDI(parent form) whenever I want to
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);
}
Child Form: Receiving the device info and displaying it
public Child(string deviceName)
{
InitializeComponent();
name_lbl.Text = deviceName
//name_lbl.Text = deviceName.ToString();
//model_lbl.Text = diviceModel;
//date_lbl.Text = manuFacturedDate;
}
CodePudding user response:
You can create two constructor. When the child form is created you can give any data or not.
public Child(string deviceName)
{
InitializeComponent();
name_lbl.Text = deviceName
}
public Child()
{
InitializeComponent();
}
CodePudding user response:
You can declare static variable in parent form outside your method,in class level - global scope, and then access that variable through the type in your child form constructor, so for example
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";
}
And then, in your child form, you can pass the value of static variable to your textbox through the default constructor, by calling 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
}