try
{
int txtno = 10;
int Textbox_pointY = 15;
int label_pointY = 15;
int label_pointX = 10;
int Textbox_pointX = 75;
panel1.Controls.Clear();
for (int i = 0; i < txtno; i++)
{ //Lable creation
Label lbl = new Label();
panel1.Controls.Add(lbl);
lbl.Text = "Test_" + i;
lbl.Location = new Point(label_pointX, label_pointY);
label_pointY += 22;
//Text box creating
TextBox a = new TextBox();
panel1.Controls.Add(a);
a.Text = (i + 1).ToString();
a.Location = new Point(Textbox_pointX, Textbox_pointY);
//panel1.Show();
Textbox_pointY += 22;
//label_pointY += 5;
}
}
catch (Exception)
{
MessageBox.Show(e.ToString());
}
在winform中动态生成标签和enter code here
文本框时c#标签重叠在文本框上。我需要将文本框保持在标签文本的附近。我在这里添加了我的代码。
答案 0 :(得分:1)
将AutoSize
设为false
并指定标签&#39;明确Width
:
int txtno = 10;
int label_pointY = 15;
int label_pointX = 10;
int Textbox_pointX = 75;
// Don't do this: it just removes conrols from the panel,
// but does't free resources (and you have resource leakage)
// panel1.Controls.Clear();
// If you want to get rid of all controls on the panel1 (i.e. dispose them)
// do it like this:
for (int i = panel1.Controls.Count - 1; i >= 0; --i)
panel1.Controls[i].Dispose();
for (int i = 0; i < txtno; i++) {
Label lbl = new Label() {
Parent = panel1,
Text = "Test_" + i,
Location = new Point(label_pointX, label_pointY),
AutoSize = false,
Width = Textbox_pointX - label_pointX,
};
TextBox box = new TextBox() {
Parent = panel1,
Text = (i + 1).ToString(),
Location = new Point(Textbox_pointX, label_pointY)
};
label_pointY += Math.Max(box.Height, lbl.Height);
}