如何在 TableLayoutPanel 中间添加行

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)
我设法将行添加到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);
}

这个无法正常工作。

我是不是做错了什么?有什么建议吗?

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);
}

非常感谢您的分享,Eldad!我也遇到了完全相同的问题。在集合的开头和结尾添加元素可以正常工作,但在开始和结束之间添加元素却失败了,这真的毫无道理...使用SetChildIndex不仅减少了很多代码,而且还非常好用 :) 再次感谢! - libjup

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接