2015-11-19 19 views
0

我有一張表格,希望每隔x秒更新一次。 要設置我希望我使用與60,120,180,240和300, 組合框的秒這應該確定秒。 計時器正在運行,沒有問題。 但是...我不能設置計時器來閱讀他必須運行的howmany秒。而且,當計時器遇到秒重啓時,這也是一個問題。 我在c#中很新,上課等,但這是我無法弄清楚的。 (抱歉我的英文不好)。 我可以在這裏得到一些幫助嗎? 這是我得到的sofare。刷新表格的計時器

_ticks++; 
label1.Text = _ticks.ToString(); 
if (_ticks == 10) 
{ 
    label1.Text = "Done"; 
} 

,這是我如何填寫組合

this.cmbRefresh.Items.AddRange(new object[] { "OFF", "60", "120", "180", "240", "300" }); 

我知道我沒有太多,但我不知道從哪裏開始。 由於事先

+1

你能給我們更多的代碼嗎?我不明白你的循環和計時器如何工作 – FKutsche

+0

也使用計時器來填充文本框/修改一個.......可能會導致相當一些問題(如你需要考慮的:「gui thread」,「timer線程「,.... – Thomas

回答

0

Handle the ComboBox.SelectedIndexChanged event.你可以通過選擇組合框,點擊F4的屬性,切換到活動標籤,雙擊SelectedIndexChanged事件。

在處理程序中使用int.Parse(this.comboBox1.SelectedItem.ToString())來獲取秒數並將其乘以一千,並使用this.timer1.Interval = sec * 1000來更新間隔。

在解析到int之前,分別使用if處理「OFF」值,因爲int.Parse將無法​​使用它。

0

你可以使用一個定時器:

Timer timer = new Timer; 
timer.Elapsed += OnTimerEvent; 

計時器事件回調:

void OnTimerEvent(Object source, ElapsedEventArgs e) 
{ 
    // Refresh 
} 

然後,當用戶改變組合框,開始計時

string t = cmbRefrest.SelectedItem.ToString(); 
if ("OFF" == t) timer.Enabled = false; 
else { 
    int timeout = Int32.Parse(t) * 1000; 
    timer.Interval = timeout; 
    timer.Enabled = true; 
} 
0

所以我想你想每次更改組合框時都要更新,爲此你可以簡單地創建一個事件處理程序fo r「SelectedIndexChanged」事件。

private void cmbRefresh_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    if (cmbRefresh.Text != "OFF")//If the combobox text is not "OFF" 
    { 
     timer1.Interval = int.Parse(cmbRefresh.Text) * 1000;//Set the interval to x seconds (value is multiplied by 1000 because timer intervals are set to milliseconds). 
    } 
    else//If the combobox text is "OFF" 
    { 
     timer1.Enabled = false;//Stop the timer. 
    } 
} 
0

在Timer上使用interval屬性,並處理Timer.Tick和ComboBox SelectedIndexChanged事件來更新標籤。間隔是時間量,以毫秒爲單位,計時器將等待,直到提高Tick事件。

您需要在此添加邏輯以確保該值爲整數。

組合變化:

timer.Interval = Convert.ToInt32(this.cmbRefresh.SelectedValue) * 1000; 

處理蜱和安全更新的標籤。

private void timer_Tick(object sender, EventArgs e) 
    { 
     var thisTimer = sender as Timer; 
     if (thisTimer != null) 
     { 
      _ticks++; 
      this.UpdateLabel(_ticks.ToString()); 
      if (_ticks == 10) 
      { 
       this.UpdateLabel("Done"); 
      }     
     } 
    } 

private void UpdateLabel(string text) 
{ 
    if (this.InvokeRequired) 
    { 
     this.Invoke(new Action(() => this.UpdateLabel(text)); 
    } 
    else 
    { 
     this.label1.Text = text; 
    } 
}