我想在其他课程中做一些事情时更新文本框。让我把我的代码:
namespace TestApp
{
public partial class Form1 : Form
{
CalledClass call = new CalledClass();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
call.Call_UpdateBox();
}
public void UpdateBox()
{
textBox1.Text = "hello";
}
}
}
namespace TestApp
{
class CalledClass
{
public void Call_UpdateBox()
{
Form1 mainform = new Form1();
//do looping for doing some tasks here and update textbox every time
mainform.UpdateBox();
}
}
}
当单击主窗体上的按钮时,将调用CalledClass中的Call_UpdateBox函数,我必须在其中执行一些循环,并在更新主窗体中的文本框之间。虽然如果我在调试模式下看到它的值,文本框会更新,但它在主窗体上保留空白。请建议。 Thx提前。
答案 0 :(得分:4)
您正在声明Form1
的新实例,而不是引用已存在的实例。你应该:
namespace TestApp
{
public partial class Form1 : Form
{
CalledClass call = new CalledClass();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
call.Call_UpdateBox(this);
}
public void UpdateBox()
{
textBox1.Text = "hello";
}
}
}
namespace TestApp
{
class CalledClass
{
public void Call_UpdateBox(Form1 Sender)
{
//do looping for doing some tasks here and update textbox every time
sender.UpdateBox();
}
}
}
答案 1 :(得分:2)
您正在创建一个新的表单实例,甚至不显示它。所以你不是在好的对象实例上调用UpdateBox()
。
相反,请重新使用您mainForm
的当前实例。例如:
public void Call_UpdateBox(Form1 targetForm)
{
targetForm.UpdateBox();
}
private void button1_Click(object sender, EventArgs e)
{
call.Call_UpdateBox(this);
}
答案 2 :(得分:1)
您可以使用Threads
但更简单的方法,因为您在WindowsForms中使用的是BackgroundWorker,
你的Form1会像:
public partial class Form1 : Form
{
BackgroundWorker _bw = new BackgroundWorker();
CalledClass call = new CalledClass();
public Form1()
{
InitializeComponent();
bw.DoWork += bw_DoWork;
bw_ProgressChanged += bw_ProgressChanged;
}
private void button1_Click(object sender, EventArgs e)
{
if (bw.IsBusy != true)
{
bw.RunWorkerAsync();
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
call.Call_UpdateBox();
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
textBox1.Text = "hello";
// Here you can access some progress property from CalledClass in order to monitor and inform progress
}
}
答案 3 :(得分:1)
最简单的方式
namespace TestApp
{
public partial class Form1 : Form
{
CalledClass call = new CalledClass();
public Form1()
{
InitializeComponent();
call.FormH = this;
}
private void button1_Click(object sender, EventArgs e)
{
call.Call_UpdateBox();
}
public void UpdateBox()
{
textBox1.Text = "hello";
}
}
}
namespace TestApp
{
class CalledClass
{
public static Form1 FormH;
public void Call_UpdateBox()
{
//do looping for doing some tasks here and update textbox every time
FormH.UpdateBox();
}
}
}