我正在尝试将文本框从名为“hex”的类更新到主窗体。在“十六进制”类中,我有以下代码:
Main m = new Main();
m.updateTextBox(convertedHex);
代码将变量传递给主窗体,传递给名为“updateTextBox”的方法,如下所示:
public void updateLog(string input)
{
textBox2.AppendText(input);
}
抱歉,如果这看起来像是一个愚蠢的问题,我已经被困了一段时间,我的谷歌搜索中的所有链接现在都是紫色的,所以我希望有人能向我解释这个问题。非常感谢。
最佳答案
在创建文本框的主类中添加这种方法,并从外部调用它。
假设您在 Program.cs
类中添加了代码以开始新的
// Add this code in Program.cs (or similar where you start the gui
public static readonly Main MainLogWindow = new Main();
// Add this code in Main.cs class
private delegate void NameCallBack(string varText);
public void UpdateTextBox(string input) {
if (InvokeRequired) {
textBox.BeginInvoke(new NameCallBack(UpdateTextBox), new object[] {input});
} else {
textBox.Text = input;
// textBox.Text = textBox.Text + Environment.NewLine + input // This might work as append in next line but haven't tested so not sure
}
}
像这样调用它:Program.MainLogWindow.UpdateTextBox("test test");
假设您打开了 MainLogWindow
这也将允许您从其他线程中调用更新。
关于c# - 从另一个类更新文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9345083/