Reputation: 537
I'm using a container (mdi parent) to open up a main menu. The main menu allows the user to connect to a database and open other programs. I'm trying to display what database you are connected to on the container (parent form) but i'm having issues passing the string from main menu to the container. When the user clicks the connect button, I somehow need the container to have an event listener to listen for a button click from the child form. When the connect button is clicked on the child form, it will pass the variable to the parent. How would I go about doing this?
Upvotes: 3
Views: 7558
Reputation: 1755
Maybe you can use an event. So each time the database name changes on the child form you can get a call back on the parent form
Child
public partial class Child : Form
{
public event DatabaseChangeHandler DatabaseChanged;
public delegate void DatabaseChangeHandler(string newDatabaseName);
public Child()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//When the database changes
if (this.DatabaseChanged != null)
{
this.DatabaseChanged("The New Name");
}
}
}
Parent
public partial class Parent : Form
{
private Child childForm;
public Parent()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// Open the child form
childForm = new Child();
childForm.DatabaseChanged += childForm_DatabaseChanged;
childForm.ShowDialog();
}
void childForm_DatabaseChanged(string newDatabaseName)
{
// This will get called everytime you call "DatabaseChanged" on child
label1.Text = newDatabaseName;
}
}
Upvotes: 9
Reputation: 461
Just declare a public variable Eg: var1 in Form2 and on selection of rows from Grid assign the selected value to the Form2 public variable var1.
Then Once you close the Form2. You can access the values in Form1 by say you have a textbox in Form1 which should get the selected value from grid of Form2 by mentioning as
Form2 f2=new Form2();
TextBox1.Text=f2.var1;
Hope this helps
Upvotes: 0