C#TableLayoutPanel - 填充和复制行控件

时间:2016-12-15 01:37:08

标签: c# tablelayoutpanel

好的 - 我再来一次 - C#newbie par Excellence!

假设我有一个 TableLayoutPanel - 只有一行,还有多个列...... 我用控件(标签,文本框等)填充该单行。

现在我想重复该行' n'时间,并将每个控件索引为数组(控件)的成员 - 例如labelName [rowIndex] .Text ="新文本"

  • 有更好的方法吗??

1] 非常感谢 - 我多年前用VB6做的最后一次尝试!

1 个答案:

答案 0 :(得分:1)

一种方法是创建List<List<Control>>。然后,您填充tablelayoutpanel的每一行都将位于List<Control>中。假设3列,它看起来像这样:

List<List<Control>> contrlList = new List<List<Control>>();
for (int row = 0; row < tableLayoutPanel1.RowCount; row++)
{
    List<Control> rowControls = new List<Control>()
        {
            new DateTimePicker(),
            new TextBox(),
            new Label()
        };
    for (int col = 0; col < tableLayoutPanel1.ColumnCount; col++)
    {
        tableLayoutPanel1.Controls.Add(rowControls[col], col, row);
        contrlList.Add(rowControls);
    }
}

要访问公共属性,您可以这样称呼它:

contrlList[0][1].Text = "Whatever";

要获得每种控件类型的特定属性,您必须将其强制转换为正确的类型:

((DateTimePicker)contrlList[0][0]).CalendarTitleBackColor = Color.AliceBlue;

要创建每种控件都可以使用的事件处理程序,请在设计器中加载其中一种类型。在属性窗口中,在标题中,是一个看起来像闪电的图标。这将显示此类控件将具有的事件列表。双击要处理的事件。这将在代码中创建一个片段。重命名方法,使其不指向该控件的特定实例(即ComboBox_SelectedIndexChanged而不是comboBox1_SelectedIndexChanged)。现在,添加该事件处理程序是一件简单的事情,以便控件知道该事件的位置。

List<List<Control>> contrlList = new List<List<Control>>();
for (int row = 0; row < tableLayoutPanel1.RowCount; row++)
{
    DateTimePicker newDTP = new DateTimePicker();
    ComboBox newCB = new ComboBox();
    newCB.SelectedIndexChanged += comboBox_SelectedIndexChanged;
    Label newL = new Label();
    List<Control> rowControls = new List<Control>()
        {
            newDTP,
            newCB,
            newL
        };
    for (int col = 0; col < tableLayoutPanel1.ColumnCount; col++)
    {
        tableLayoutPanel1.Controls.Add(rowControls[col], col, row);
        contrlList.Add(rowControls);
    }
}