2012-02-12 6 views
0

런타임에 컨트롤을 폼에 추가하려고합니다. 코딩 영역 안의 Form에 컨트롤을 추가하는 함수를 만들었습니다. 값을 다른 많은 형식으로 사용할 수 있도록 클래스의 함수를 호출해야합니다.클래스에서 폼에 컨트롤을 추가하는 함수 호출

클래스에서 : 양식에서

public void AddControl(string ControlTxt) 
    { 
     Form1 frm1 = new Form1(); 
     frm1.AddButton(ControlTxt); 
    } 

: 여기에 코드입니다 내가 button1에 클릭하면

public void AddButton(string TxtToDisplay) 
    { 

     Button btn = new Button(); 
     btn.Size = new Size(50, 50); 
     btn.Location = new Point(10, yPos); 
     yPos = yPos + btn.Height + 10; 
     btn.Text = TxtToDisplay; 
     btn.Visible = true; 
     this.Controls.Add(btn); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     Class1 cls1 = new Class1(); 
     cls1.AddControl("Hello"); 
    } 

코드가 작동하지 않습니다는 그것은 어떤을 보여주는 아니에요 예외. 양식의 AddButton 함수를 클래스에서 호출하는 방법은 무엇입니까?

답변

2

기본 양식이 사용자 정의 Form 클래스에서 새로 추가 된 경우 this.AddButton()을 사용할 수 있습니다.

이제 폼의 새로운 초기화 작업을하고 있지만 어디에도 표시하지 않을 것입니다.

실제로 오류가 발생하지 않는 이유이기도합니다. 응용 프로그램이 프로그래밍 된대로 작동하지만 새로 만든 양식이 절대로 창으로 설정되거나 표시되도록 설정되지 않습니다. (코드에 근접하는 동안)

1

당신은 모든 클릭으로 새 양식을 작성하는 (대신에 현재의 양식을 사용)하는, 나는 이런 식으로 할 것 :

public class SomeClass 
{ 
    public static void AddControl(Form form, string controlTxt) 
    { 
     form.AddButton(form, controlTxt); 
    } 

    public static void AddButton(string form, string TxtToDisplay) 
    { 

     Button btn = new Button(); 
     btn.Size = new Size(50, 50); 
     btn.Location = new Point(10, yPos); 
     yPos = yPos + btn.Height + 10; 
     btn.Text = TxtToDisplay; 
     btn.Visible = true; 
     form.Controls.Add(btn); 
    } 
} 


private void button1_Click(object sender, EventArgs e) 
{ 
    SomeClass.AddControl(this, "Hello"); 
} 
관련 문제