2012-02-12 7 views
0

実行時にいくつかのコントロールをフォームに追加しようとしています。私は、コーディング領域内のフォームにコントロールを追加する関数を作成しました。値を他の多くの形式で使用できるように、クラスから関数を呼び出す必要があります。ここでは、コードは次のようになります。クラスからフォームにコントロールを追加する関数を呼び出す

クラスで

:フォームで

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

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

私は、コードが動作しないbutton1をクリックして、いずれかを表示していないとき例外。 フォームのAddButton機能をクラスから呼び出すにはどうすればよいですか?

答えて

2

メインフォームが新しいカスタムフォームクラスである場合は、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"); 
} 
関連する問題