user3714977
user3714977

Reputation: 109

How to define a timers interval from a textbox in C#

I am learning C# and I am coding a simple auto typer, and I am trying to make it so users' can set their own interval. I tried using:

timer1.Interval = textbox1.Text;

but that doesn't seem to be working. I put that code in a button.. How do I get this to work? And why isn't it working?

Upvotes: 1

Views: 3825

Answers (2)

Ramy M. Mousa
Ramy M. Mousa

Reputation: 5941

try this :

Timer timer1 = new Timer();
timer1.Interval = int.Parse(textbox1.Text);

but keep in mind that user must enter a number , so you might need to handle the case when the user enter wrong data .

Edit : You might use TryParse to make sure it's a number :

int myInt = 0;
Timer timer1 = new Timer();
bool parsed = int.TryParse(textbox1.Text,out myInt);

if (parsed)
{
    timer1.Interval = myInt;
}

Upvotes: 3

Markus Safar
Markus Safar

Reputation: 6592

You could use something like this:

int value;

// if it is really a value
if (int.TryParse(textbox1.Text, out value))
{
    // if the value is not negativ (or you can enter the lower boundary here)
    if (value > 0)
    {
        timer1.Interval = value;
    }
}

As Steve mentioned in his comment, you need to connect a callback function to the timer1.Elapsed event (Attention: The name of the event differs depending on the timer you are using. It could also be timer1.Tick). You would do this by using the following code:

timer1.Elapsed += TimerElapsedCB;

and you need to define the callback function itself:

private void TimerElapsedCB(object sender, ElapsedEventArgs e)
{
    // Do something here ;-)
    // (e.g. access the signal time by using e.SignalTime)
}

Upvotes: 5

Related Questions