从计时器中的c#中的另一个类访问表单的文本框值

时间:2016-07-13 13:30:01

标签: c# winforms 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)
    {

    }
}

3 个答案:

答案 0 :(得分:0)

因此,您需要获取要修改文本的表单实例。您可以通过将引用传递给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 :(得分:0)

检查此SO线程 - How to access Winform textbox control from another class?

  1. 基本上公开更新文本框

  2. 的公共属性
  3. 公开文本框

  4. 另请注意,您需要更新UI线程中的表单控件

答案 2 :(得分:0)

这里有一些问题,但两者都很容易解决。

问题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帖子中指出您有关于该问题以及如何修复问题的详细信息:Cross-thread operation not valid