2011-11-01 134 views
5

我有3列和1列一個TableLayoutPanel的中間: (刪除按鈕,用戶控件添加按鈕)如何將行添加到一個TableLayoutPanel

我想添加按鈕來添加類似於新行上述下方點擊的按鈕: 例如: BEFORE:

  1. (刪除按鈕1,用戶控制2,添加按鈕1)
  2. (刪除按鈕2,用戶控制2,添加按鈕2)

點擊 「添加按鈕1」 之後:

  1. (刪除按鈕1,用戶控制2,添加按鈕1)
  2. (刪除按鈕3,用戶控制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); 
} 

這並不正常工作。

我做錯了什麼?有什麼建議麼?

回答

6

終於找到了解決辦法:不是添加控件以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); 
} 
+0

+1非常感謝你分享,Eldad!我有完全相同的問題。它只是沒有任何意義,爲什麼添加元素在集合的開始和結束工作,但在開始和結束之間的任何地方失敗... SetChildIndex不僅拿走了很多代碼,但也像一個魅力:) thx再次! – libjup

+0

很高興我能幫忙:) – Eldad

相關問題