5

我有一个 3 列和 1 行的 TableLayoutPanel:(删除按钮、用户控件、添加按钮)

我希望添加按钮在单击的按钮下方添加类似于上面的新行:例如:之前:

  1. (删除按钮 1、用户控件 2、添加按钮 1)
  2. (删除按钮 2、用户控制 2、添加按钮 2)

点击“添加按钮1”后:

  1. (删除按钮 1、用户控件 2、添加按钮 1)
  2. (删除按钮 3、用户控制 3、添加按钮 3)
  3. (删除按钮 2、用户控制 2、添加按钮 2)

我设法将该行添加到 tablelayopanel 的末尾,但没有添加到中间:它一直在搞砸布局。这是事件处理程序的片段:

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 回答