如何将行添加到一个TableLayoutPanel
问题描述:
我有3列和1列一个TableLayoutPanel的中间: (删除按钮,用户控件添加按钮)如何将行添加到一个TableLayoutPanel
我想添加按钮来添加类似于新行上述下方点击的按钮: 例如: BEFORE:
- (删除按钮1,用户控制2,添加按钮1)
- (删除按钮2,用户控制2,添加按钮2)
点击 “添加按钮1” 之后:
- (删除按钮1,用户控制2,添加按钮1)
- (删除按钮3,用户控制3,添加按钮3)
- (删除按钮2,用户控制2,添加按钮2)
我设法将该行添加到tablelayounel的结尾,但不是中间:它不断拧紧布局。 这里的事件处理程序的一个片段:
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);
}
这并不正常工作。
我做错了什么?有什么建议么?
答
终于找到了解决办法:不是添加控件以thier直接的位置,我将它们添加到年底,然后使用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);
}
+1非常感谢你分享,Eldad!我有完全相同的问题。它只是没有任何意义,为什么添加元素在集合的开始和结束工作,但在开始和结束之间的任何地方失败... SetChildIndex不仅拿走了很多代码,但也像一个魅力:) thx再次! – libjup
很高兴我能帮忙:) – Eldad