Reputation: 141
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();
}
}
}
Upvotes: 0
Views: 198
Reputation: 596156
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();
Upvotes: 0
Reputation: 14618
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...
}
Upvotes: 0
Reputation: 596
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
Upvotes: 5