简体   繁体   中英

C# Forms add text to textbox from other class

I have a C# Form called Form1.cs and a Class in the same project called RandWord.cs.

Now I want to add text to the textbox (tbRandom) from the class.

I added the following code to Form1.cs:

    public TextBox tbRandom;

And the following code to the 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());
   }
}

The messagebox is just there to prove that the Int is not empty. But the textbox won't display anything. There is no Exception aswell. The class is called by a button ( RandWord(); )

Any ideas?

You can write a contractor method for your class and pass the TextBox to it, and you can access the TextBox from there.

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

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

In you 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);
    } 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM