0

I am new to C# and I am trying to understand the timer feature.. I made a label, a textbox and a button also added a timer ofcourse.

I have a int set to 1000 = 1 second.

I would like to be able to enter a value into the textbox i.e 5 and then the timer uses that as its interval between every tick.

For some reason its saying "Cannot implicitly convert type "string to int"

And I have no idea on how to convert a string to an int..

Any examples? Would help me so much!

namespace Clicker
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int count = 0;
        int interval = 1000;


        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            timer1.Start();
            interval = textBox1.Text;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            count++;
            label1.Text = count.ToString();

        }
    }
}
  • 3
    Possible duplicate of [How can I convert String to Int?](http://stackoverflow.com/questions/1019793/how-can-i-convert-string-to-int) – Cyril Iselin May 20 '16 at 15:30

3 Answers3

5
 interval = textBox1.Text;

interval is an integer and textBox1.Text is a string. You have to parse the value like:

interval = int.Parse(textBox1.Text)

or better use int.TryParse!

also you can find this here: String to Integer

Community
  • 1
  • 1
Cyril Iselin
  • 596
  • 4
  • 20
0

The error is self explanatory. You are trying to assign a string to an int. Specifically, on this line:

interval = textBox1.Text;

You need to use the Int32.Parse() method to convert the string data:

interval = Int32.Parse(textBox1.Text) * 1000;

That being said, you are not actually using your interval variable for anything. You need to assign the timer's Interval property before starting the timer:

interval = Int32.Parse(textBox1.Text) * 1000;
timer1.Interval = interval;
timer1.Start();
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0

interval is of type int. The property Text on the TextBox control is a string.

You need to convert/parse the value to an int to use it e.g:

int userInput = 0;

if(Int32.TryParse(textBox1.Text, out userInput))
{
    interval = userInput;
}
else
{
    // Input couldn't be converted to an int, throw an error etc...
}
DGibbs
  • 14,316
  • 7
  • 44
  • 83