[英]access form's text box value from another class in c# in timer
我想将DateTime显示在“ Form1”形式的文本框中。我创建了一个“ schedule”类来创建一个间隔为1秒的计时器。 但是无法访问和更新Form1的文本框字段“ xdatetxt”。 我不明白为什么它不能访问Form1中的控件xdatetxt。
Schedule.cs
class Schedule{
System.Timers.Timer oTimer = null;
int interval = 1000;
public Form anytext_Form;
public Schedule(Form anytext_form)
{
this.anytext_Form = anytext_form;
}
public void Start()
{
oTimer = new System.Timers.Timer(interval);
oTimer.Enabled = true;
oTimer.AutoReset = true;
oTimer.Start();
oTimer.Elapsed += new System.Timers.ElapsedEventHandler(oTimer_Elapsed);
}
private void oTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{//i want to put here a line like "anytext_Form.xdatetxt.Text = System.DateTime.Now.ToString();"
}
}
在form1.cs中:
public partial class Form1 : Form{
public Form1()
{
InitializeComponent();
InitializeScheduler();
}
void InitializeScheduler()
{
Schedule objschedule = new Schedule(this);
objschedule.Start();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
因此,您需要获取要修改文本的表单的实例。 您可以通过传递对objschedule的引用或使用Application.openforms
。
如果已经引用了表单,则第一种方法是完美的,但是如果没有,则只需:
private void oTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
dynamic f = System.Windows.Forms.Application.OpenForms["anytext_Form"];
f.xdatetxt.Text=System.DateTime.Now.ToString();
}
这里有一些问题,但是都可以直接解决。
问题1:通过其基类引用表单
Schedule
类的构造函数采用Form
一个实例。 那是Form1
类的基类,并且没有xdatetxt
字段。 更改您的Schedule
构造函数以接受并存储Form1
的实例:
public Form1 anytext_Form;
public Schedule(Form1 anytext_form)
{
this.anytext_Form = anytext_form;
}
问题2:从非UI线程更新控件
修复编译器错误后,将遇到运行时错误。 原因是Timer
类在后台线程上执行其回调。 您的回调方法尝试从该后台线程访问UI控件,这是不允许的。
我可以在此提供内联的解决方案,但我将带您到另一篇StackOverflow帖子中,其中包含有关该问题及其解决方法的更多详细信息: 跨线程操作无效 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.