C#从左到右填充TableLayoutPanel单元格

时间:2013-05-15 13:21:49

标签: c# winforms tablelayout

我正在开发一个Windows窗体应用程序,它主要由一个包含8列和9行的TableLayoutPanel组成。我已经能够像这样填充每个单元格:

for (int row = 0; row < TableLayoutPanel.RowCount; row++) {
    for (int column = 0; column < TableLayoutPanel.ColumnCount; column++) {
        PictureBox pictureBox = new PictureBox();
        pictureBox.BackColor = Color.Blue;
        TableLayoutPanel.Controls.Add(pictureBox, column, row);
        pictureBox.Dock = DockStyle.Fill;
        pictureBox.Margin = new Padding(1);
}

然而,这种方法从顶部开始,而不是从左到右,如:

1 2 3
4 5 6

我的目标是填写TableLayoutPanel,如:

6 5 4
1 2 3

我不知道这是否可行,但有没有办法以这种方式填充TableLayoutPanel单元格?

2 个答案:

答案 0 :(得分:0)

尝试用以下代码替换for循环:

for (int row = TableLayoutPanel.RowCount - 1, c0 = 0, c1 = TableLayoutPanel.ColumnCount - 1, cs = 1; row >= 0 ; row--, c0 ^= c1, c1 ^= c0, c0 ^= c1, cs *= -1)
{
    for (int column = c0; column != c1 + cs; column += cs)
    {
         ...

答案 1 :(得分:0)

别担心,我知道怎么做。我做的是我从TableLayoutPanel的底行开始(在我的例子中是row = 8)并从那里开始工作。我确定行值是奇数还是偶数,在这种情况下我会改变方向。这是解决方案。

for (int row = TableLayoutPanel.RowCount-1; row >= 0; row--) {
    if (row % 2 == 0) { //if even
        for (int column = 0; column < TableLayoutPanel.ColumnCount; column++) {
            PictureBox pictureBox = new PictureBox();
            pictureBox.BackColor = Color.Blue;
            TableLayoutPanel.Controls.Add(pictureBox, column, row);
            pictureBox.Dock = DockStyle.Fill;
            pictureBox.Margin = new Padding(1);
    } else { 
        for (int column = TableLayoutPanel.ColumnCount-1; column >= 0; column--) {
            PictureBox pictureBox = new PictureBox();
            pictureBox.BackColor = Color.Blue;
            TableLayoutPanel.Controls.Add(pictureBox, column, row);
            pictureBox.Dock = DockStyle.Fill;
            pictureBox.Margin = new Padding(1);
    }
}