I have a TableLayoutPanel with 3 columns and 1 row: (Remove button, User Control, Add button)
I want the Add button to add a new row similar to the above below the clicked button: e.g: BEFORE:
After clicking"Add button 1":
I managed to add the row to the end of the tablelayoupanel but not to the middle: It keeps screwing up the layout. Here's a snippet of the event handler:
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);
}
This doesn't work properly.
Am I doing something wrong? any suggestions?
Finally found a solution: Instead of adding the controls to thier direct location, I'm adding them to the end and then use the SetChildIndex()
function to move the control to the desired location:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With