-2
以下代碼是主要問題的概念。我想要做的是,當有人按下按鈕1時,啓用計時器不斷更改label1的值。現在主要的問題是我需要從TimerEventProcessor()訪問表單元素,如標籤,文本框,但我不能這樣做。我嘗試使用Form1 formm = new Form1();但仍然不起作用。沒有東西顯示,我也沒有得到任何錯誤。如何從方法中獲取表單標籤
static Timer mytimer = new Timer();
static int counter= 1;
private static void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{ mytimer.Enabled = true;
Form1 formm = new Form1();
formm.label1.Text = counter;
counter++;
}
private void button1_Click(object sender, EventArgs e)
{
myTimer.Tick += new EventHandler(TimerEventProcessor);
myTimer.Interval = 1000;
myTimer.Start();
}
刪除*靜態*關鍵字。現在很簡單,就是「this.label1」。 – 2013-03-25 19:46:49
或者如果您需要'TimerEventProcessor'是靜態的,在您的應用程序命名空間中定義了一個靜態變量,並設置它的價值,你的''上的負載Form'例如Form'(即寫'yourStaticVariable = this'上'Form'負載) – fardjad 2013-03-25 19:49:33
這幾乎違背了使用靜態方法的目的。即使你想要一個Form1的Singleton實例,字段和事件處理程序也應該是非靜態的。 – 2013-03-25 19:59:28