我想自动调整一些生成的控件。我创建了两种TextBox
类型和两种CustomControl
类型,它们是UserControl
. 每个CustomControl
都有一个Label
显示我称之为标题的字符串。我只能看到两个文本框之一。我只能看到两个标题之一。如何显示表单中的所有控件?我不喜欢自己管理控制位置。而是坚持Dock
设置。
public partial class SomeForm : Form
{
public SomeForm()
{
InitializeComponent();
LoadControls();//I can only see the first control caption and textBox2
//how can I display both textboxes and both captions?
}
private void LoadControls()
{
TextBox textBox = GenerateTextBox("First textbox");
TextBox textBox2 = GenerateTextBox("Second textbox");
CustomControl control = new CustomControl(labelCaption: "First control caption");
CustomControl control2 = new CustomControl(labelCaption: "second control caption");
//add the textboxes to the usercontrols
control.Controls.Add(textBox);
control2.Controls.Add(textBox2);
//this displays only 1 control (incorrect)
flowLayoutPanel1.Controls.Add(control);
flowLayoutPanel1.Controls.Add(control2);
flowLayoutPanel1.SetFlowBreak(control, true);
flowLayoutPanel1.SetFlowBreak(control2, true);
//this displays both controls (correct)
//flowLayoutPanel1.Controls.Add(textBox);
//flowLayoutPanel1.Controls.Add(textBox2);
//flowLayoutPanel1.SetFlowBreak(textBox, true);
//flowLayoutPanel1.SetFlowBreak(textBox2, true);
}
private static TextBox GenerateTextBox(string text)
{
TextBox textBox = new TextBox();
textBox.Text = text;
textBox.Dock = DockStyle.Top;
return textBox;
}
}
自定义控件:
public CustomControl(string labelCaption)
{
InitializeComponent();
Label label = new Label();
label.Text = "Rtb..." + labelCaption;
//label.Dock = DockStyle.Top;
//contentPanel.Controls.Add(label);//disabled for now
}