5

3列1行のTableLayoutPanelがあります:([削除]ボタン、[ユーザーコントロール]、[追加]ボタン)

[追加]ボタンで、クリックしたボタンの下に上記のような新しい行を追加します。例:BEFORE:

  1. (ボタン1を削除、ユーザーコントロール2、ボタン1を追加)
  2. (ボタン2を削除、ユーザーコントロール2、ボタン2を追加)

「ボタン1を追加」をクリックした後:

  1. (ボタン1を削除、ユーザーコントロール2、ボタン1を追加)
  2. (ボタン3を削除、ユーザーコントロール3、ボタン3を追加)
  3. (ボタン2を削除、ユーザーコントロール2、ボタン2を追加)

私はなんとかtablelayoupanelの最後に行を追加しましたが、中央には追加しませんでした。それはレイアウトを台無しにし続けます。イベントハンドラのスニペットは次のとおりです。

void MySecondControl::buttonAdd_Click( System::Object^ sender, System::EventArgs^ e )
{
   int rowIndex = 1 + this->tableLayoutPanel->GetRow((Control^)sender);

   /* Remove button */
   Button^ buttonRemove = gcnew Button();
   buttonRemove->Text = "Remove";
   buttonRemove->Click += gcnew System::EventHandler(this, &MySecondControl::buttonRemove_Click);

   /* Add button */
   Button^ buttonAdd = gcnew Button();
   buttonAdd->Text = "Add";
   buttonAdd->Click += gcnew System::EventHandler(this, &MySecondControl::buttonAdd_Click);

   /*Custom user control */
   MyControl^ myControl = gcnew MyControl();

   /* Add the controls to the Panel. */
   this->tableLayoutPanel->RowCount += 1;
   this->tableLayoutPanel->Controls->Add(buttonRemove, 0, rowIndex);
   this->tableLayoutPanel->Controls->Add(myControl, 1, rowIndex);
   this->tableLayoutPanel->Controls->Add(buttonAdd, 2, rowIndex);
}

これは正しく機能しません。

私は何か間違ったことをしていますか?助言がありますか?

4

1 に答える 1

6

最後に解決策を見つけました。コントロールを直接の場所に追加する代わりに、最後に追加してから、SetChildIndex()関数を使用してコントロールを目的の場所に移動します。

void MySecondControl::buttonAdd_Click( System::Object^ sender, System::EventArgs^ e )
{
   int childIndex = 1 + this->tableLayoutPanel->Controls->GetChildIndex((Control^)sender);

   /* Remove button */
   Button^ buttonRemove = gcnew Button();
   buttonRemove->Text = "Remove";
   buttonRemove->Click += gcnew System::EventHandler(this, &MySecondControl::buttonRemove_Click);

   /* Add button */
   Button^ buttonAdd = gcnew Button();
   buttonAdd->Text = "Add";
   buttonAdd->Click += gcnew System::EventHandler(this, &MySecondControl::buttonAdd_Click);

   /*Custom user control */
   MyControl^ myControl = gcnew MyControl();

   /* Add the controls to the Panel. */
   this->tableLayoutPanel->Controls->Add(buttonRemove);
   this->tableLayoutPanel->Controls->Add(myControl);
   this->tableLayoutPanel->Controls->Add(buttonAdd);

   /* Move the controls to the desired location */
   this->tableLayoutPanel->Controls->SetChildIndex(buttonRemove, childIndex);
   this->tableLayoutPanel->Controls->SetChildIndex(myControl, childIndex + 1);
   this->tableLayoutPanel->Controls->SetChildIndex(buttonAdd, childIndex + 2);
}
于 2011-11-06T11:45:34.507 に答える