简体   繁体   中英

TableLayoutPanel only shows last row - C#

I've a TableLayoutPanel that has 10 rows and 2 columns.

My problem is, when I add a label in the first column and a button in the other, everything is fine. But when I add another label and a button on eg the next row, the previous rows are empty. It seems that my program only shows to last added row.

Code:

Label lblProjectName = new Label();
lblProjectName.Text = "test";
lblProjectName.Anchor = AnchorStyles.Left;
Button btnProject = new Button();
btnProject.Text = "Fill In";

tlpProject.Controls.Add(lblProjectName, 0, 0);
tlpProject.Controls.Add(btnProject, 1, 0);

tlpProject.Controls.Add(lblProjectName, 0, 1);
tlpProject.Controls.Add(btnProject, 1, 1);

Tnx!

You have to create a new control for each cell in the panel.

Currently, your code is moving the controls to the last column and last row.

Something like this:

for (int i = 0; i < numRows; ++i) {
  Button btnProject = new Button();
  btnProject.Text = "Fill In";
  tlpProject.Controls.Add(btnProject, 1, i);
}

Any event handlers would have to be added here too, where on the handler end, you have to check the "sender" of the object to see which button the user pressed.

It seems like Label and Button can only be children to single control while you are adding them into different cells(thus different controls). If you need all cells filled with Labels and Buttons you will need 10 Labels and 10 Buttons for each column. Look at the code:

for(int i=0;i<10;i++){
var lblProjectName = new Lable();
lblProjectName.Text = "test";
lblProjectName.Anchor = AnchorStyles.Left;
var btnProject = new Button();
btnProject.Text = "Fill In";

tlpProject.Controls.Add(lblProjectName, 0, i);
tlpProject.Controls.Add(btnProject, 1, i);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM