2017-08-30 46 views
0

所以,我对编程有点新,并且正如标题所述,尝试为面板添加标签,这两个标签都是在运行时通过按钮点击创建的在C#中。也许文本框更好,但它不应该做这样的区别。我已经找到了一些有用的答案,但总的来说,面板在运行之前就已经创建好了。c#在运行时在面板上添加一个标签

所以,我的问题是:当我编写代码时,如何在没有创建面板的情况下如何将标签添加到面板上,并使用 newLabel.Parent = panel_name;。那么是否可以在面板上添加更多标签或itembox?

这里是我的完整代码按钮点击:

// 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!"); 
     } 
    } 

回答

1

你应该试试这个:

myPanel.Controls.Add(newLabel); 

而是家长设置为名称的??您应该将标签添加到面板(子控件)。就像您将面板添加到this.Controls.Add(myPanel);中一样,这两个都来自Control并支持子控件。

+0

Thx。适合我。 – Sakul

相关问题