2016-05-13 17 views
-1

Form1.csというC#フォームとRandWord.csという同じプロジェクトにクラスがあります。C#フォームは他のクラスのテキストボックスにテキストを追加します

ここで、クラスのテキストボックス(tbRandom)にテキストを追加します。

私はForm1.csのに次のコードを追加しました:

public TextBox tbRandom; 

そしてクラスに次のコード:

public RandWord() 
{ 
    //get linecount 
    int linesGerman = File.ReadAllLines(pathGerman).Length; 
    int linesFrance = File.ReadAllLines(pathFrance).Length; 
    //check if same linecount 
    if (linesGerman == linesFrance) 
    { 
     //new random int 
     Random rnd = new Random(); 
     int rndLine = rnd.Next(1, File.ReadAllLines(pathGerman).Length); 
     //write to Form1's Textbox tbWord 
     f1.tbRandom.Text = rndLine.ToString(); 
     MessageBox.Show(rndLine.ToString()); 
    } 
} 

をメッセージボックスがintが空でないことを証明するためにそこにあります。しかし、テキストボックスには何も表示されません。例外はありません。クラスはボタンで呼び出されます(RandWord();)

アイデア?

+1

は、単にテキストボックスを宣言し、サイズと位置を設定せず、 'それはたぶん形 –

+1

に表示されことはありませんf1'はあなたが見るのと同じインスタンスではありません。また、フォームに 'TextBox'が表示されない場合は、フォームにコントロールを追加することを忘れているかもしれません。関連するコードの残りの部分を共有する。 –

+0

あなたの質問にもっとコードを書いてください。これは明確ではありません – mohsen

答えて

0

FROM1:

 public TextBox tbRandom =new TextBox() ; 
    private void Form1_Load(object sender, EventArgs e) 
    { 
     this.Controls.Add(tbRandom); 
    } 
    public string TextBoxTxt { 
     get { return txtText1.Text; } 
     set { txtText1.Text = value; } 
    } 
//Your button RandWord 
private void RandWord_Click(object sender, EventArgs e) 
    { 
     RandWord(this); 
    } 

あなたのクラスRandWord:

public RandWord(Form f1) 
{ 
    //get linecount 
    int linesGerman = File.ReadAllLines(pathGerman).Length; 
    int linesFrance = File.ReadAllLines(pathFrance).Length; 
    //check if same linecount 
    if (linesGerman == linesFrance) 
    { 
     //new random int 
     Random rnd = new Random(); 
     int rndLine = rnd.Next(1, File.ReadAllLines(pathGerman).Length); 
     //write to Form1's Textbox tbWord 
     f1.TextBoxTxt = rndLine.ToString(); 
     MessageBox.Show(rndLine.ToString()); 
    } 
} 
+0

それは完璧に働いてくれてありがとう! – Shad0w

+0

これを聞いてうれしい –

0

クラスの請負業者メソッドを作成してそれにTextBoxを渡すことができます。そこからTextBoxにアクセスできます。

あなたに
class GenerateRandomWord 
    { 
     TextBox _t; 
     public GenerateRandomWord(TextBox t) 
     { 
      _t = t; 
     } 

     public void RandWord() 
     { 
     _t.Text = "Something!"; 
     } 
    } 
関連する問題