我如何在运行时从其他表单的fragmentlayoutpanel中添加新按钮
private void btnNotEkle_Click(object sender, EventArgs e)
{
YeniForm yeniForm = new YeniForm();
Button btn = new Button();
yeniForm.Controls.Add(btn);
}
按钮不以JPYi形式存在。我应该在公共场所公开fraglayoutpanel吗?
答案 0 :(得分:0)
使flawLayoutPanel
成为public
会暴露出实施细节,这是一种不好的做法。我建议将Button
创建代码移至YeniForm
中:
public partial class YeniForm : Form {
...
// Let's generalize the implementation and allow to create a control,
// not neccesary button
public T CreateFlawControl<T>() where T : Control, new() {
T result = new T() {
Parent = flawLayoutPanel,
};
//TODO : set Size, Location etc here
return result;
}
}
您可以将其用作
private void btnNotEkle_Click(object sender, EventArgs e) {
YeniForm yeniForm = new YeniForm();
Button btn = yeniForm.CreateFlawControl<Button>();
...
// do not forget to show the form - yeniForm.Show() or yeniForm.ShowDialog()
}
答案 1 :(得分:0)
您可以在YeniForm
中创建用于添加按钮/控件的方法,并以以下形式实现添加:
class YeniForm : Form
{
...
public void AddButton(Button btn)
{
this.flowLayoutPanel1.Controls.Add(btn); // or whatever you need. Calc position for new control, add it to some kind of container (Panel/TableLayoutPanel etc)
}
}
private void btnNotEkle_Click(object sender, EventArgs e)
{
YeniForm yeniForm = new YeniForm();
Button btn = new Button();
yeniForm.AddButton(btn);
...
}