2010-08-02 7 views
2

패널 안에 컨트롤 (레이블)을 추가하려고합니다.폼에 프로그래밍 방식으로 컨트롤을 추가하는 방법?

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace AddControlProgramatically 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      Label lbl = new Label(); 

      for (int x = 0; x <= 3; x++) 
      { 
       //create new label location after each loop 
       //by multiplying the new value of variable x by 5, so the new label 
       //control will not overlap each other. 
       lbl.Location = new System.Drawing.Point(52 + (x * 5), 58 + (x * 5)); 
       //create new id and text of the label 
       lbl.Name = "label_" + x.ToString(); 
       lbl.Text = "Label " + x.ToString(); 

       this.panel1.Controls.Add(lbl); 
      } 
     } 
    } 
} 

screenshot

여기 폼의 : 코드를 참조하십시오. 달성하고자하는 것은 프로그래밍 방식으로 3 가지 제어 라벨을 생성하는 것입니다. 그러나 보시다시피, 마지막 것만 표시합니다. 제발 도와주세요. 내 코드에 문제가 있다는 것을 알고 있습니다. (작동하지 않기 때문에). 감사합니다 ...

+0

미안 해요에서 초보자를 answers..just 수용하는 방법을 모른다 이 포럼. 정확히 어떻게해야할까요? – yonan2236

+0

질문을 할 때 위/아래 표결 아래에 체크 표시가 있습니다. 정답을 수락하려면 체크 표시를 클릭하십시오. 그것은 사용자에게 추가적인 포인트를 제공 할뿐만 아니라 비슷한 문제가있을 때 어떤 답이 작동하는지 다른 사람들에게 알립니다. –

+0

고마워요. – yonan2236

답변

5

Label lbl = new Label();을 루프 안에 넣습니다. 에

그리고이 변화, 더 큰 오프셋 만들 ...

lbl.Location = new System.Drawing.Point(52 + (x * 5), 58 + (x * 5)) 

... :

lbl.Location = new System.Drawing.Point(52 + (x * 30), 58 + (x * 30)) 
+0

지금 작동 중입니다.) 감사합니다 ... – yonan2236

+0

많이 환영합니다 :-) –

2

각 루프 반복에서 새 레이블을 만들어야합니다. 지금은 하나의 라벨 만 만들고 있습니다.

private void button1_Click(object sender, EventArgs e) 
{ 
    for (int x = 0; x <= 3; x++) 
    { 
     Label lbl = new Label(); 

     //create new label location after each loop 
     //by multiplying the new value of variable x by 5, so the new label 
     //control will not overlap each other. 
     lbl.Location = new System.Drawing.Point(52 + (x * 5), 58 + (x * 5)); 
     //create new id and text of the label 
     lbl.Name = "label_" + x.ToString(); 
     lbl.Text = "Label " + x.ToString(); 

     this.panel1.Controls.Add(lbl); 
    } 
} 
+0

방금 ​​말한대로했는데 아무런 변화가 없었습니다 ... – yonan2236

+0

그것은 작동하지 않습니다. – yonan2236

+0

흠, 4 개의 라벨이 만들어 져야합니다. ('x <= 3'). –

0

당신은 당신의 for 루프 내에서 Label lbl = new Label();을 넣어해야합니다.

+0

ok thanks ...... :) – yonan2236

+0

방금 ​​말한대로했지만 아무런 변화가 없습니다 ... – yonan2236

+0

작동 중입니다 ... 덕분에 – yonan2236

관련 문제