【问题标题】:C# TableLayoutPanel - populate and duplicate row controlsC# TableLayoutPanel - 填充和复制行控件
【发布时间】:2016-12-17 12:44:27
【问题描述】:

好的 - 我又来了 - C# 新手出类拔萃!

假设我有一个如图所示的 TableLayoutPanel - 有一行,多列... 我用控件(标签、文本框等)填充该单行。

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

  • 有没有更好的方法...?

非常感谢 - 我最后一次尝试这样做是在多年前使用 VB6!

【问题讨论】:

    标签: c# tablelayoutpanel


    【解决方案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;
    

    要创建每种类型的控件都可以使用的事件处理程序,请在设计器中加载该类型的一种。在属性窗口的标题中,是一个看起来像闪电的图标。这会显示此类控件将具有的事件列表。双击您要处理的事件。这将在代码中创建一个 sn-p。重命名该方法,使其不指向该控件的特定实例(即 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);
        }
    }
    

    【讨论】:

    • 好的 - 让我考虑一下!这一切都说得通,但不如我预期的那么直观/可读。
    • 是的,我喜欢这种相对简单的方式。我知道上面建议使用列表控件,但是对于像我这样的笨蛋来说,您的帖子更具可读性!
    • 我已经设法让它工作了,但我有另一个转折点,这通常可以解决一些问题......假设一些加载的控件是组合框......我该如何填充它们(并在它发生变化时得到一个事件。
    • 我为你添加了更多。为了填充组合框,按照我的示例,将列表中的控件、作为组合框的行、列索引转换为组合框,并像任何组合框一样添加项目。
    • 谢谢 - 当你在它的时候 - 我也想通了。 - 非常感谢
    猜你喜欢
    • 2015-12-01
    • 2013-05-10
    • 1970-01-01
    • 1970-01-01
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    相关资源
    最近更新 更多