一种方法是创建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);
}
}