2017-08-30 11 views
0

私はちょっとプログラミングに慣れていますが、タイトルにすでに書かれているように、ラベルをパネルに追加するには、両方ともランタイムにbuttonclick C#で。たぶんテキストボックスが優れているかもしれませんが、そのような違いはありません。私はすでにいくつかの有益な答えを見つけましたが、一般的には、パネルはランタイムの前にすでに作成されています。c#実行時にパネルにラベルを追加する

私の問題は次のとおりです。 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!"); 
     } 
    } 

答えて

1

あなたはこれを試してみてください:

myPanel.Controls.Add(newLabel); 

代わりに名前に親を設定するの?。?パネル(子コントロール)にラベルを追加する必要があります。 から派生し、子コントロールをサポートしているフォームthis.Controls.Add(myPanel);にパネルを追加したのと同じです。あなたがオブジェクトを操作している

+0

Thx。私のために素晴らしい作品。 – Sakul

関連する問題