【问题标题】:How do I pass a Timer to an EventHandler?如何将 Timer 传递给 EventHandler?
【发布时间】:2011-05-10 20:09:44
【问题描述】:

我想要的是有一个ComboBox,它在SelectedIndexChanged 上会改变一个Timer.Interval。我的代码基本上是这样的:

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 变量的引用。

如何修改我的代码以将AutoRefresh 传递给comboBox1_SelectedIndexChanged()

也许是指出我还是 C# 新手的好时机。请善待。

【问题讨论】:

  • 你为什么要这样做?你想达到什么目的?如果您解释,可能会给出一个更好的方法来实现它的答案。
  • @Oded - 好电话。该程序非常简单:刷新后它会查询一个 SQL DB,该数据库填充一个 DataTable 以供显示。我想使用这个组合框和 Timer 在重复发生的计时器上自动刷新 DataTable,并且我希望在用户选择新的时间表(4 小时、2 小时、1 小时、15 分钟)后立即更新 Timer 的间隔。
  • 你看过SqlDependency类吗?
  • @Oded - 我没有,但在阅读了 20 秒后,我认为SqlDependency 就像一个 SQL 查询的侦听器并报告更改是否正确?
  • 差不多 - 更改通过事件发出信号。

标签: c# event-handling parameter-passing


【解决方案1】:

一种方法是将 Time 对象声明为类的成员。然后你就可以在事件中访问它了。

你也应该删除'throw new NotImplementedException();'来自您的事件,因为此语句引发异常

【讨论】:

    【解决方案2】:

    在字段中提取局部变量表单构造函数,现在计时器将在处理程序中可见

    Timer AutoRefresh;   
    public Form1()
    {
      InitializeComponent();
     AutoRefresh = new Timer();
      AutoRefresh.Tick += new EventHandler(AutoRefresh_Tick);
    
     resh.Interval = 10000;
      AutoRefresh.Enabled = true;
    

    }

    【讨论】:

    • 您可能尝试在构造函数之外对其进行初始化。每当您遇到构建错误时,阅读它
    【解决方案3】:

    根据您的评论,SqlDependency 类可能对您很有效:

    ...程序...查询填充DataTable 以进行显示的SQL DB。我想用这个组合框和 Timer 来自动刷新 DataTable ...

    【讨论】:

      【解决方案4】:

      您需要将计时器放入您班级的field

      【讨论】:

        【解决方案5】:

        我在你的代码中发现一个错误

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

        【讨论】:

          【解决方案6】:

          我做了一些重构,发现代码中有另一个错误 看看这个方法在我的项目中可以正常工作

          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 属性而不是 SelectedText

          【讨论】:

            【解决方案7】:
            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;
                    }
                }
            }
            

            【讨论】:

              猜你喜欢
              • 2021-11-29
              • 1970-01-01
              • 2012-01-28
              • 1970-01-01
              • 2013-06-21
              • 1970-01-01
              • 1970-01-01
              • 2020-11-28
              • 1970-01-01
              相关资源
              最近更新 更多