我有一个名为Form1.cs的C#表单和一个名为RandWord.cs的同一个项目中的类。
现在我想从课程中添加文本到文本框(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();)
有什么想法吗?
答案 0 :(得分:0)
您可以为您的类编写承包方法并将TextBox传递给它,您可以从那里访问TextBox。
class GenerateRandomWord
{
TextBox _t;
public GenerateRandomWord(TextBox t)
{
_t = t;
}
public void RandWord()
{
_t.Text = "Something!";
}
}
答案 1 :(得分: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());
}
}