首页 > 解决方案 > 组合框的定时器间隔更改

问题描述

我在组合框中有项目。当我选择该项目时,计时器间隔必须乘以组合框中选择的数字。但是当运行代码时,它会显示“System.ArgumentOutOfRangeException:'Value'0' 不是 Interval 的有效值。Interval 必须大于 0。” 组合框中的项目是 1、2、4、8、10 和 20。

代码如下

int x1;
        private int ch1xscale()
    {
        x1 = Convert.ToInt32(cmbch1.SelectedItem);
        return x1;

    }

timer1.Tick += Timer1_Tick;
        timer1.Interval = 100*ch1xscale();
        

        cmbch1.SelectedIndex = 3;

这里有什么问题?

标签: c#timer

解决方案


让我给你举个例子。如果您根据此示例设置代码,它将毫无问题地工作。只需尝试设置interval并且不要更改计时器类的其他示例变量。

仅仅因为计时器是一个线程,我不得不使用 adelegate来同步以使用其他控件。

1.创建计时器

Timer timer;
public delegate void InvokeDelegate();
int x1;
public Form1()
{
    InitializeComponent();

    timer = new Timer();
    timer.Tick += Timer_Tick;
    timer.Interval = 100;
    timer.Start();
}
private int ch1xscale()
{
    x1 = Convert.ToInt32(cmbch1.SelectedItem);
    return x1;
}

2.定时器滴答

private void Timer_Tick(object sender, EventArgs e)
{
   //do work
   this.BeginInvoke(new InvokeDelegate(InvokeMethod));
}
void InvokeMethod()
{
     myLabel.Text = timer.Interval.ToString();
}

3.combobox选中改变事件

private void cmbTimer_SelectedIndexChanged(object sender, EventArgs e)
{         
    timer.Stop();
    timer.Interval = 100 * ch1xscale();
    timer.Start();           
}

推荐阅读