2017-12-09 4 views
-2

버튼을 드래그 앤 드롭하는 것은 쉽지만 강사는 버튼을 프로그래밍 방식으로 작성해야한다고 주장했습니다.C# 윈도우 응용 프로그램에서 프로그래밍 방식으로 버튼을 만들려면 어떻게해야합니까?

Form1_Load 메서드에서 간단한 단추를 만들기 위해 어떤 코드를 써야합니까?

private void Form1_Load(object sender, System.EventArgs e) 
{ 

} 

로드시에 버튼이 표시됩니다. 당신이 윈폼이다 말했듯이

+0

이 윈폼입니다을 넣어? –

+0

예 윈도우 폼 –

+1

[동적으로 여러 버튼을 wpf 창에 추가 하시겠습니까?] (https://stackoverflow.com/questions/5929710/dynamically-add-multiple-buttons-to-wpf-window) –

답변

1

, 다음 ...

먼저 새로운 Button 객체를 생성 할 수 있습니다.

Button newButton = new Button();

그런 다음 사용하여 해당 함수 내 양식에 추가 : 사용자가 설정할 수

this.Controls.Add(newButton);

추가 속성 ...

newButton.Text = "Created Button"; 
newButton.Location = new Point(70,70); 
newButton.Size = new Size(50, 100); 

문제 실행중인 제품을 to는 Form_Load 이벤트에서 설정하려고 시도하는 것입니다.이 단계에서는 양식이 아직 존재하지 않고 버튼이 덮어 쓰기됩니다. 단추를 표시하려면 Shown 또는 Activated 이벤트에 대한 대리인이 필요합니다. 당신이 당신의 버튼을 생성하고 폼에 추가 어디 Form1 생성자 내부 예를 들어

,

public Form1() 
{ 
    InitializeComponent(); 
    this.Shown += CreateButtonDelegate; 
} 

귀하의 실제 대표가이 같은 작동합니다.

private void CreateButtonDelegate(object sender, EventArgs e) 
{ 
    Button newButton= new Button(); 
    this.Controls.Add(newButton); 
    newButton.Text = "Created Button"; 
    newButton.Location = new Point(70,70); 
    newButton.Size = new Size(50, 100); 
    newButton.Location = new Point(20, 50); 
} 
+0

네임 스페이스 SimplePiano { 공용 부분 클래스 Form1 : 양식 { 단추 nb = 새 단추(); public Form1() { InitializeComponent(); } private void Form1_Load (개체 보낸 사람, System.EventArgs) { this.Controls.Add (nb); } –

+0

코드를 실행할 때 버튼을 표시하지 않습니다. 메서드 외부에 button 객체를 만든 다음 Load() 메서드에서 this.controls.add (newButton)를 수행했지만 작동하지 않았습니다. –

+0

@KurtCamilleri 내 편집을 참조하십시오. – Adriani6

-1

그것은 간단하다 : 당신의 eventload 양식에

private void Form1_Load(object sender, System.EventArgs e) 
{ 
    Button btn1 = new Button(); 
    this.Controls.add(btn1); 
    btn1.Top=100; 
    btn1.Left=100; 
    btn1.Text="My Button"; 

} 
+0

불행히도 그것은 작동하지 않았다. –

+0

왜? @ KurtCamilleri. 무엇이 문제였습니까? – nAviD

+0

Windows Form을 실행할 때 버튼이 표시되지 않습니다. –

1

이 코드

private void Form1_Load(object sender, EventArgs e) 
    { 
     Button testbutton = new Button(); 
     testbutton.Text = "button1"; 
     testbutton.Location = new Point(70, 70); 
     testbutton.Size = new Size(100, 100); 
     testbutton.Visible = true; 
     testbutton.BringToFront(); 
     this.Controls.Add(testbutton); 

    } 
+0

나는 곧 테스트 할 것입니다. –

관련 문제