2011-05-10 7 views
1

ComboBoxSelectedIndexChanged 일 때 Timer.Interval으로 변경됩니다. 내 코드는 기본적으로 다음과 같습니다타이머를 EventHandler에 전달하는 방법은 무엇입니까?

public Form1() 
{ 
    InitializeComponent(); 
    Timer AutoRefresh = new Timer(); 
    AutoRefresh.Tick += new EventHandler(AutoRefresh_Tick); 
    var RefreshIntervals = new[] { "4 hours", "2 hours", "1 hour", "15 minutes", "10 seconds" }; 
    comboBox1.DataSource = RefreshIntervals; 
    comboBox1.SelectedIndexChanged += new EventHandler(comboBox1_SelectedIndexChanged); 
} 

void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    if (AutoRefresh.Enabled == true) 
     AutoRefresh.Enabled = false; 
    if (comboBox1.SelectedText == "4 hours") 
     AutoRefresh.Interval = 14400000; 
    else if (comboBox1.SelectedText == "2 hours") 
     AutoRefresh.Interval = 7200000; 
    else if (comboBox1.SelectedText == "1 hour") 
     AutoRefresh.Interval = 3600000; 
    else if (comboBox1.SelectedText == "15 minutes") 
     AutoRefresh.Interval = 900000; 
    else if (comboBox1.SelectedText == "10 seconds") 
     AutoRefresh.Interval = 10000; 
    AutoRefresh.Enabled = true; 
} 

을 이제 comboBox1_SelectedIndexChanged()Timer 변수에 대한 참조가 없기 때문에 분명이 작동하지 않습니다.

AutoRefreshcomboBox1_SelectedIndexChanged()으로 전달하려면 코드를 어떻게 수정할 수 있습니까?

아마도 나는 C#으로 초보자라는 것을 지적하기에 좋은시기입니다. 친절 하구만.

+0

왜 이러는거야? 무엇을 성취하려고합니까? 설명하면, 더 좋은 방법으로 그것을 얻을 수 있습니다. – Oded

+0

@Oded - 전화하세요. 이 프로그램은 매우 간단합니다 : 새로 고침시 DataTable을 채우는 SQL DB를 쿼리하여 표시합니다. 이 comboBox와 Timer를 사용하여 자동으로 Reoccurring 타이머에서 DataTable을 새로 고치고 사용자가 새 일정 (4 시간, 2 시간, 1 시간, 15 분)을 선택하자마자 Timer 's Interval을 업데이트하려고합니다. – newuser

+1

['SqlDependency'] (http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldependency.aspx) 클래스를 보았습니까? – Oded

답변

1

SqlDependency 클래스가 잘 작동 할 수 있습니다에 볼 수 있습니다 당신이 만든 코멘트에 따라 :

...이 프로그램은 ... 표시를 위해 DataTable을 채우는 SQL DB를 쿼리합니다. 나는

0

수업 시간에 field에 타이머를 넣어야합니다.

2

한 가지 방법으로 Time 객체를 클래스의 멤버로 선언 할 수 있습니다. 그러면 이벤트 내에서 액세스 할 수 있습니다.

또한 'not throw new NotImplementedException();'을 삭제해야합니다. 이 사항이 예외가 발생하기 때문에 이벤트에서

2

는 필드에 로컬 varible 양식 생성자를 추출하고 지금 타이머 핸들러

Timer AutoRefresh; 
public Form1() 
{ 
    InitializeComponent(); 
AutoRefresh = new Timer(); 
    AutoRefresh.Tick += new EventHandler(AutoRefresh_Tick); 

resh.Interval = 10000; 
    AutoRefresh.Enabled = true; 

}

+0

VS2010을 사용해 보았을 때 빌드를 허용하지 않을 것이라고 맹세했습니다 ... – newuser

+0

생성자 외부에서 초기화하려고 시도했을 수 있습니다. 빌드 오류가 발생할 때마다 ** ** 읽어보십시오! – SLaks

0

...이과 ComboBox 자동으로 DataTable을 새로 고침 할 수있는 타이머를 사용하려면 내가 어떤 리팩토링을했습니다

void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    throw new NotImplementedException(); // remove this line 
+0

나는 그것을 편집했다. :) – newuser

0
namespace WindowsFormsApplication1 
{ 
    using System; 
    using System.Windows.Forms; 

    public partial class Form1 : Form 
    { 
     /// <summary> 
     /// The default constructor. 
     /// I used the designer, so the InitializeComponent method contains the timer and combobox initialization. 
     /// </summary> 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     /// <summary> 
     /// Occurs when the combo box selection changes. 
     /// </summary> 
     /// <param name="sender">The sender object, i.e., the combobox</param> 
     /// <param name="e">The event arguments.</param> 
     private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
     { 
      if (autoRefresh.Enabled == true) 
      { 
       autoRefresh.Enabled = false; 
      } 

      // so I can easily change the time scale when debugging, I'm using a multiplier 
      const int multiplier = 10000; 

      // notice I'm using SelectedItem because the event triggered was index changed, not text changed 
      var selectedInterval = comboBox1.SelectedItem.ToString(); 

      // if a valid entry wasn't selected, then we'll disable the timer 
      var enabled = true; 

      switch (selectedInterval) 
      { 
       case "4 hours": 
        autoRefresh.Interval = 1440 * multiplier; 
        break; 
       case "2 hours": 
        autoRefresh.Interval = 720 * multiplier; 
        break; 
       case "1 hour": 
        autoRefresh.Interval = 360 * multiplier; 
        break; 
       case "15 minutes": 
        autoRefresh.Interval = 90 * multiplier; 
        break; 
       case "10 seconds": 
        autoRefresh.Interval = 1 * multiplier; 
        break; 
       default: 
        // we didn't choose a valid entry, or picked blank line 
        enabled = false; 
        break; 
      } 

      autoRefresh.Enabled = enabled; 
     } 

     /// <summary> 
     /// Occurs every time the timer reaches its interval 
     /// </summary> 
     /// <param name="sender">The sender object, i.e., the timer.</param> 
     /// <param name="e">The event arguments.</param> 
     private void AutoRefresh_Tick(object sender, EventArgs e) 
     { 
      // to ensure the next timer triggers at the desired interval 
      // stop the timer while doing the operations in this method (they could be lengthy) 
      // and then restart the timer before exiting 
      autoRefresh.Enabled = false; 

      // give a visual indicator of the timer ticking. 
      // Here is where you would do your DB operation. 
      MessageBox.Show(string.Format("Hello! time={0}:{1}", DateTime.Now.ToLongTimeString(), DateTime.Now.Millisecond)); 

      autoRefresh.Enabled = true; 
     } 
    } 
} 
0

당신의 코드에서 하나의 오류를 발견하고 또 다른 오류를 발견 이 방법에서 코드 보기에 괜찮 일이 내 프로젝트에있어

void comboBox1_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     if (AutoRefresh.Enabled) 
      AutoRefresh.Enabled = false; 
     var selectedItem = comboBox1.SelectedItem.ToString(); 

     switch (selectedItem) 
     { 
      case "4 hours": 
       AutoRefresh.Interval = 14400000; 
       break; 
      case "2 hours": 
       AutoRefresh.Interval = 7200000; 
       break; 
      case "1 hour": 
       AutoRefresh.Interval = 3600000; 
       break; 
      case "15 minutes": 
       AutoRefresh.Interval = 900000; 
       break; 
      case "10 seconds": 
       AutoRefresh.Interval = 10000; 
       break; 
     } 
     AutoRefresh.Enabled = true; 
    } 

당신은의 selectedItem 속성을 사용한다 선택한 텍스트를 입력하십시오

관련 문제