Reputation: 61
ok, I have 2 forms...On f1 is a flowlayoutPanel and a button that opens f2. On f2 there are small panels, each is a diffrent color. I want to do this:when I click on a panel from f2 a panel is created in FLP in f1 that has the same color and size. The problem is that when I click on the first panel on f2 nothing happens. this is what I have so far:
f1
private void Add_Color_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.Show();
}
f2
Form1 f1 = new Form1();
private void panel1_Click(object sender, EventArgs e)
{
Panel pnl = new Panel();
pnl.BackColor = panel1.BackColor;
pnl.Size = panel1.Size;
f1.BackColor = panel1.BackColor;
f1.FLPMain.Controls.Add(pnl);
this.Close();
}
Upvotes: 1
Views: 606
Reputation: 203802
So your child form shouldn't need to know a thing about your first form. It sounds like you're creating something like a generic color picker tool. You should be able to use that same form somewhere else in your application where you need to pick a color as well, for example.
As a general rule it's best if a child form doesn't "know" about it's parent, it keep them decoupled, makes it easier to write each class separately without forcing the developer to be so knowledgeable about the other types in the project. It's actually not terribly hard.
So rather than having Form2 go and add a panel to Form1, it can just notify Form1 when it's chosen a color and a size. This is done through an event:
public class Form2 : Form
{
//define the event
public event Action<Color, Size> ColorChosen;
private void panel1_Click(object sender, EventArgs e)
{
//raise the event
var panel = (Panel)sender;
ColorChosen(panel.BackColor, panel.Size);
Close();
}
}
(Size note; by using sender
here this same event handler can be added to all of the panels you want to be clickable, rather than having a ton of event handlers that do almost the same thing.)
Then on Form1 we just assign an event handler to this custom event where we create and add a new panel to the form:
Form2 child = new Form2();
child.ColorChosen += (color, size) =>
{
Panel panel = new Panel();
panel.BackColor = color;
panel.Size = size;
Controls.Add(panel);
};
child.Show();
Upvotes: 1
Reputation: 3967
Just do it this way
private void Add_Color_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(this);
f2.Show();
}
class Form2
{
private Form1 _frm;
public Form2(Form1 frm)
{
//initialize + other code if required
_frm = frm;
}
private void Panel_Click(object sender, EventArgs e)
{
_frm.CreatePanel(/*param you need*/); //name it what ever you want
}
}
bassicaly something like that should do the job
/e there might be some typos but the idea is there
Upvotes: 0
Reputation: 1425
You're creating a new instance of Form1 here:
Form1 f1 = new Form1();
But you want to add your panels on the existing one, so use:
Form f1 = Application.OpenForms['formname'];
Upvotes: 0