开发者

How do I pass a Timer to an EventHandler?

What I want is to have a ComboBox which, upon SelectedIndexChanged, changes a Timer.Interval. My code basically looks like this:

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)
开发者_如何学Go        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;
}

Now, obviously this doesn't work because comboBox1_SelectedIndexChanged() doesn't have a reference to a Timer variable.

How can I modify my code to pass AutoRefresh to comboBox1_SelectedIndexChanged()?

Probably a good time to point out that I'm still a novice with C#. Please be kind.


One way could be to declare the Time object as a member of class. Then you will be able to access it inside event.

also you should remove 'throw new NotImplementedException();' from you event because this statement throws an exception


Extract the local varible form constructor in a field and now timer will be visible in the handler

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

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

}


The SqlDependency class may work well for you, based on the comment you made:

... The program ... queries a SQL DB which fills a DataTable for display. I want to use this comboBox and the Timer to automatically refresh the DataTable ...


You need to put the timer into a field in your class.


I found one error in you code

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


I've made some refactoring and found another error in code look at this method it's work ok in my project

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;
    }

you should use the SelectedItem property insteed SelectedText


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜