我需要动态地向
据我所知,
-
有没有一种方法可以结合
TableLayoutPanel
添加许多Control
对象,这需要相当长的时间。我还需要能够通过TableLayoutPanel
的行列索引来访问控件,反之亦然。据我所知,
TableLayoutPanel.Controls
有三种方法来添加Control
对象:-
.Add(Control)
- 继承而来,位置为-1,-1,使用.GetCellPosition(Control)
获取位置。
- .Add(Control, column, row)
- 位置和索引正确,但可能有点慢?
- .AddRange (Control[])
- 继承而来,速度更快,显示位置正确(每个单元格都被填充,必要时设置跨列),但使用.GetCellPosition(Control)
获取位置时为-1,-1。有没有一种方法可以结合
.Add(Control, column, row)
和 .AddRange(Control[])
的优点,即快速向 TableLayoutPanel
添加大量 Control
对象,同时仍然能够以编程方式获取 Control
的位置?
编辑 包含一些来自评论的信息:
- 最多添加了1000个控件
- 我已经使用了
SuspendLayout()
和ResumeLayout()
TableLayoutPanel
需要大约2秒钟才能加载。 根据分析器,大约50%的时间用于添加控件,20%用于ResumeLayout()
编辑:MCVE
我的原始代码更加复杂,但这是一个TableLayoutPanel
的例子,其中添加控件占用了大部分时间(2/3)。我正在寻找一种加速此过程的方法。
public class FormTLPTest : Form
{
public FormTLPTest()
{
Height = 800;
Width = 800;
TableLayoutPanel tlp = new TableLayoutPanel();
tlp.Dock = DockStyle.Fill;
tlp.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;
tlp.AutoScroll = true;
Controls.Add(tlp);
tlp.ColumnCount = 7;
tlp.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 20));
tlp.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100.0F));
tlp.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 80));
tlp.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 100));
tlp.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 30));
tlp.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 70));
tlp.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 20));
tlp.SuspendLayout();
for (int i = 0; i<700; i++)
{
Button btn1 = new Button();
Label lb2 = new Label();
Label lb3 = new Label();
Label lb4 = new Label();
TextBox tb5 = new TextBox();
Button btn6 = new Button();
Button btn7 = new Button();
foreach (Control c in new Control[] { btn1, lb2, lb3, lb4, tb5, btn6, btn7})
{
c.Margin = new Padding();
c.Dock = DockStyle.Fill;
c.BackColor = Color.White;
}
btn1.FlatStyle = FlatStyle.Flat;
btn6.FlatStyle = FlatStyle.Flat;
btn7.FlatStyle = FlatStyle.Flat;
btn1.Text = "1";
lb2.Text = "Some longer Text - it contains information. Don't know what I should write to fill the space";
lb3.Text = "Short Text";
lb4.Text = "Short Text";
tb5.Text = "5";
btn6.Text = "Button";
btn7.Text = "+";
tlp.Controls.Add(btn1, 0, i);
tlp.Controls.Add(lb2, 1, i);
tlp.Controls.Add(lb3, 2, i);
tlp.Controls.Add(lb4, 3, i);
tlp.Controls.Add(tb5, 4, i);
tlp.Controls.Add(btn6, 5, i);
tlp.Controls.Add(btn7,6, i);
}
tlp.ResumeLayout();
}
}
AddRange
只是一个用Suspend/ResumeLayout
包围的Add
循环。 - Ivan Stoev