我无法更新我的 WinForm 标签属性。
详细信息:我正在尝试检查我的数据库并发布一些值,但似乎我什至无法仅更新标签。我正在使用 SharpDevelop。
编码:
//this is my form
public partial class MainForm : Form
{
//Declaring timer
public static System.Timers.Timer aTimer = new System.Timers.Timer();
public MainForm()
{
InitializeComponent();
//Timer
aTimer.Elapsed +=new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = 2000; //milisecunde
aTimer.Enabled = true;
label1.Text="some_text";
}
private static void OnTimedEvent(object source, ElapsedEventArgs e) {Check();}
public static void Check()
{
//Database checks here..
try{label1.Text="new_text";}catch(Exception e) {MessageBox.Show(e.ToString());}
MessageBox.Show("BAAAA");
}
void Button1Click(object sender, EventArgs e)
{
label1.Text = "mergeeeeee?!";
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:我已经删除了所有静态修饰符。还用新代码更新了帖子(添加了 try catch 和后面的消息框 + 一个更改标签的按钮)。尝试捕获以下错误:

. 真的可以使用一些帮助,已经研究了 6 个多小时的答案。
试试这个(使用 aSystem.Windows.Forms.Timer而不是System.Timers.Timer):
//Declaring timer
public System.Windows.Forms.Timer aTimer = new System.Windows.Forms.Timer();
public Form1()
{
InitializeComponent();
//Timer
aTimer.Tick += aTimer_Tick;
aTimer.Interval = 2000; //milisecunde
aTimer.Enabled = true;
label1.Text = "some_text";
}
void aTimer_Tick(object sender, EventArgs e)
{
Check();
}
public void Check()
{
try
{
//Database checks here..
label1.Text = string.Format("new_text {0}", DateTime.Now.ToLongTimeString());
}
catch (Exception ex)
{
throw ex;
}
MessageBox.Show("BAAAA");
}
Run Code Online (Sandbox Code Playgroud)
的Elapsed事件System.Timers.Timer是在非 UI 线程上触发的(将您的原始代码更改为不吞下异常,您应该会看到跨线程异常)。
| 归档时间: |
|
| 查看次数: |
4084 次 |
| 最近记录: |