[英]How to Drag, Drop and Resize Label on a Panel at runtime? C#, winForms
[英]c# add a label to a panel both at the runtime
因此,我对编程有点陌生,正如标题所说,我尝试在面板上添加标签,这两个标签都是在运行时通过c#中的clickclick创建的。 也许文本框会更好,但是它不应该做这样的改变。 我已经找到了一些有用的答案,但是总的来说,总是在运行时之前已经创建了面板。
因此,我的问题是:如何使用newLabel.Parent = panel_name;
将标签添加到面板中newLabel.Parent = panel_name;
当我编写代码时还没有创建面板。 然后可以在面板上添加更多标签或项目框吗?
这是按钮点击的完整代码:
// for dragging the panels during runtime
Point move;
Label[] labels = new Label[1000];
Panel[] panels = new Panel[1000];
// To Remove the last created panel
List<Panel> panelsAdded = new List<Panel>();
// increments by one for each created label
int counter = 0;
// sets the posstion in the window for each created panel
int counterpos_x = 50;
int counterpos_y = 50;
// converted string from the combobox where I want to get the text for the label
string str_installation;
// my try... doesn't work
string panel_name;
private void btnCreate_Click(object sender, EventArgs e)
{
if(counter < 40)
{
Panel myPanel = new Panel();
myPanel.Tag = "Panel" + counter;
myPanel.Location = new Point(counterpos_x,counterpos_y)
myPanel.Height = 150;
myPanel.Width = 200;
myPanel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
panel_name = "Panelnumber" + counter;
// how do I need to declare this for the label to inherit with newLabel.Parent = panel_name
myPanel.Name = panel_name;
// for dragging the panel
myPanel.MouseMove += new MouseEventHandler(myPanel_MouseMove);
myPanel.MouseDown += new MouseEventHandler(myPanel_MouseDown);
panels[counter] = myPanel;
this.Controls.Add(myPanel);
// to remove the latest panel
panelsAdded.Insert(0, myPanel);
// convert the selected combobox item into a string for label
str_installation = this.cbAnlagen.GetItemText(this.cbAnlagen.SelectedItem);
// create label
Label newLabel = new Label();
newLabel.Name = "testLabel";
newLabel.Text = str_installation;
newLabel.AutoSize = true;
// !!here's the problem with the exception CS0029!!
newLabel.Parent = panel_name;
counterpos_x += 225;
if(counter % 8 == 0)
{
counterpos_y += 175;
counterpos_x = 50;
}
counter++;
}
else
{
MessageBox.Show("Maximale Anzahl an Anlagen erreicht.", "Achtung!");
}
}
您应该尝试这样:
myPanel.Controls.Add(newLabel);
而不是将父项设置为“名称”。 您应该将标签添加到面板(子控件)。 就像您将面板添加到表单this.Controls.Add(myPanel);
它们均来自Control
并支持子控件。
您正在使用对象,每个面板实例都是Panel类的一个对象
https://msdn.microsoft.com/it-it/library/system.windows.forms.panel(v=vs.110).aspx
每个面板实例都有一个属性“ .Controls”,方法为“ Add(control)
所以你必须执行这行
parentPanel.Controls.Add(labelToAdd)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.