Как динамически добавить кнопку из дочерней формы в основную форму - PullRequest
0 голосов
/ 17 мая 2019

Я хочу добавить действующую 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 голосов
/ 17 мая 2019

Во-первых, вы должны найти основную форму (при условии, что вы работаете с 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();
    }
  }
  ...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...