如何从子窗体动态添加按钮到主窗体

时间:2019-05-17 09:42:32

标签: c# winforms

当我在另一种形式上的Button中选择一个项目时,我想在我的主形式中添加一个起作用的ListView

我在ListView表单上放置了以下代码,但是由于选择该项目时什么也没发生,因此我不确定自己做对了吗。

Point newLoc = new Point(5,5);  

Button b = new Button();
b.Size = new Size(10, 50);
b.Location = newLoc;
newLoc.Offset(0, b.Height + 5);
Controls.Add(b);

1 个答案:

答案 0 :(得分:0)

首先,您必须找到主表单(假设您正在使用 WinForms ):

 using System.Linq;

 ...

 //TODO: Put the right type instead of MyMainForm
 MyMainForm mainForm = Application
   .OpenForms
   .OfType<MyMainForm>()
   .LastOrDefault();      // If there many opened main forms, let's use the last one

然后,如果找到该表单,让我们添加一个按钮:

public partial class MyChildForm : Form {
  // It seems it should be a field to store the next button position
  private Point newLoc = new Point(5, 5);  

  private Button addButtonToMainForm() {
    //TODO: Put the right type instead of MyMainForm
    MyMainForm mainForm = Application
     .OpenForms
     .OfType<MyMainForm>()
     .LastOrDefault();    

    // If Main Form has been found, let's add a button on it
    if (mainForm != null) {
      Button b = new Button() {
        Size     = new Size(10, 50), 
        Location = newLoc,
        Parent   = mainForm, // Place the button on mainForm
      }

      newLoc.Offset(0, b.Height + 5);

      return b;
    }

    return null;
  }

  private void myListView_ItemSelectionChanged(object sender,
                                               ListViewItemSelectionChangedEventArgs e) {
    // If item selected (not unselected) 
    if (e.Item.Selected) {
      //TODO: Some other conditions which on the item that has been selected 
      // Button on the Main Form, null if it hasn;t been created
      Button createdButton = addButtonToMainForm();
    }
  }
  ...