C# 表单从其他 class 添加文本到文本框

C# Forms add text to textbox from other class

我在名为 RandWord.cs 的同一个项目中有一个名为 Form1.cs 的 C# 窗体和一个 Class。

现在我想从 class 添加文本到文本框 (tbRandom)。

我在 Form1.cs 中添加了以下代码:

    public TextBox tbRandom;

并将以下代码添加到class:

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不为空。但是文本框不会显示任何内容。也没有例外。 class 由按钮调用 ( RandWord(); )

有什么想法吗?

您可以为您的 class 编写一个承包商方法并将 TextBox 传递给它,然后您可以从那里访问 TextBox。

    class GenerateRandomWord
    {
       TextBox _t;
       public GenerateRandomWord(TextBox t)
       {
           _t = t;
       }

        public void RandWord()
        {
         _t.Text = "Something!";
        }
    }

在你 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);
    } 

您的 class 随机词:

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