【问题标题】:Error in clicking event presenting the current TIme in TextBox单击在 TextBox 中显示当前时间的事件时出错
【发布时间】:2015-10-12 01:13:07
【问题描述】:

好的,所以我想获取当前时间,然后将其放入我在单击按钮后在 Windows 窗体中创建的 TextBox 中。到目前为止,我已经得到了这么多。但是我遇到了很多问题,我已经放弃了,所以我来这里寻求帮助。顺便说一句,这甚至可能吗?

错误

1) 'OnTimedEvent' 匹配委托没有重载 'System.Timers.ElapsedEventHandler'

2) 成员 'Time.Form1.button1_Click(object, System.EventArgs)' 不能 通过实例引用访问;用类型名称限定它 而是

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Time {
    public partial class Form1: Form {
        public Form1() {
            InitializeComponent();
        }
        public static System.Timers.Timer aTimer;
        private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e, TextBox textBox1) {
            textBox1.Text = DateTime.Now.ToString("h:mm:ss tt");
        }
        public static void button1_Click(object sender, EventArgs e) {
            aTimer = new System.Timers.Timer(1000);
            aTimer.Elapsed += OnTimedEvent;
            aTimer.AutoReset = true;
            aTimer.Enabled = true;
        }
    }
}

【问题讨论】:

  • "我想要获取当前时间,然后将其放入文本框中" 这里没有理由使用System.Timers.Timer,而是使用System.Windows.Forms.Timer,因为它将在主 UI 线程中运行.

标签: c# winforms visual-studio-2010 time textbox


【解决方案1】:

您更改了 OnTimedEvent() 方法的签名,这将不起作用。

删除最后一个参数,并从您当前拥有的所有 3 个位置删除 static 关键字。

那么下面的事件方法应该可以工作:

private void OnTimedEvent(Object source, ElapsedEventArgs e)
{
    textBox1.Text = DateTime.Now.ToString("h:mm:ss tt");
}

【讨论】:

  • 附加:您在此文件中看不到它,但 textBox1 已经是此类的私有成员。这意味着您不必在此类中创建的任何方法中传递它。应该有一个 Form1.designer.cs 文件。这就是您通过 WYSIWYG 设计器将所有内容放到表单上的地方。
  • 啊,是的。接得好。我错过了那里的静态关键字。 @Incin - 你可能不需要或不想要一个静态变量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-01
  • 2016-08-27
  • 2021-03-26
  • 2017-03-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多