-1

I have items in a combo box. When I selected the item, the timer interval must be multiplied by the number selected in the combo box. But when run the code it says "System.ArgumentOutOfRangeException: 'Value '0' is not a valid value for Interval. Interval must be greater than 0." the items in the combo box are 1,2,4,8,10 and 20.

the code is below

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

    }

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

        cmbch1.SelectedIndex = 3;

what is wrong here ?

Buddhika
  • 1
  • 3

1 Answers1

0

Let me give you an example. If you set your code according to this example, it will work without any problems. Just try to set the interval and do not change the other sample variables of the timer class.

Just because the timer is a thread I had to use a delegate to synchronize to use the other controls.

1.create timer

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.timer tick

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

3.combobox selected changed event

private void cmbTimer_SelectedIndexChanged(object sender, EventArgs e)
{         
    timer.Stop();
    timer.Interval = 100 * ch1xscale();
    timer.Start();           
}
Meysam Asadi
  • 6,438
  • 3
  • 7
  • 17
  • @meyasam asadi: It worked as in the given part 3. But I had to use Convert.ToInt32 instead of ToDouble as it an error occured "CS0266 Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)". I faced the same problem even before this question is posted. How to include the double type variables here. My Interval type is milliseconds. – Buddhika Mar 09 '21 at 07:37
  • I used System.Timers.Timer whose Interval received a double value. I changed it according to your code. I modified the code. This is what you want now. – Meysam Asadi Mar 09 '21 at 07:47