2016-09-18 3 views
1

私はc#windowsアプリケーションを作っていて、プログラムでフォーム(例:TextBoxとLabel)でオブジェクトを作成しようとしています。私はこれを簡単に行うことができますが、私はそれらを公開オブジェクトとして定義することはできません。私は「varstats」と呼ばれるクラスに「makeTextBox(...)」と呼ばれる機能を持っており、これは、関数である:c#で関数を使って作成したオブジェクトにアクセスする方法

public static void makeTextBox(Panel pnlMain, int offsetTop, int offsetRight, string strName = "") 
    { 
     TextBox txt = new TextBox(); 
     txt.Name = strName; 
     txt.Parent = pnlMain; 
     txt.AutoSize = true; 
     txt.Width = (pnlMain.Width - 9 * defdis)/3; //defdis is a public int and means default distance 
     txt.Location = new Point(pnlMain.Width - txt.Width - defdis - offsetRight - 3, offsetTop + defdis); 
    } 

そして、これは、フォーム負荷での私のメインフォームのコードです:

varstats.makeTextBox(pnlMain, 0, 0, "txtCustName"); 

この機能は非常に動作します正しく(:D)、私はPanel内のTextBoxを見ることができますが、どのようにTextBoxにアクセスできますか?たとえば、別のフォームでTextBoxのtextプロパティを読んでそれを私のデータベースに保存する必要がありますか?これを行う方法?

私はクラスのヘッダーに定義することはできませんが、forやwhileを使用してオブジェクトをあまりにもたくさん作成したい場合や、それらを削除して別のオブジェクトを作成したい場合もあるためです。

答えて

1

最も簡単な方法は、あなたの方法からテキストボックスを返すと、それを使用することです:

// return is changed from void to TextBox: 
public static TextBox makeTextBox(Panel pnlMain, int offsetTop, int offsetRight, string strName = "") 
{ 
    TextBox txt = new TextBox(); 
    txt.Name = strName; 
    txt.Parent = pnlMain; 
    txt.AutoSize = true; 
    txt.Width = (pnlMain.Width - 9 * defdis)/3; //defdis is a public int and means default distance 
    txt.Location = new Point(pnlMain.Width - txt.Width - defdis - offsetRight - 3, offsetTop + defdis); 

    // return the textbox you created: 
    return txt; 
} 

そして今、あなたは変数にメソッドの戻り値を代入し、それをあなたが望む任意の方法を使用することができます

TextBox myTextBox = varstats.makeTextBox(pnlMain, 0, 0, "txtCustName"); 

// for example, change the text: 
myTextBox.Text = "Changed Text"; 
+0

私は 'preparePanel'と呼ばれる別の関数を持っていますが、この関数はさまざまな型(TextBox、Label、DataGridViewなど)であまりにも多くのコントロールを作成し、この関数は' makeLabel'や....私は 'preparePanel'関数でさまざまなコントロールの配列を返す必要があります。そのような配列を持つことは可能ですか? – KamyarM

+0

私は答えを見つけました([Here](http://stackoverflow.com/questions/11395315))。あなたの答えをありがとう。 :) – KamyarM

関連する問題