Monday, May 24, 2010

What is wrong with this C# code?

I need to get the input of this textbox (which is supposed to be minutes) multiply it by 60, and then output it to textbox2. I get this error though:


Error 1 Cannot implicitly convert type 'int' to 'string'








private void Start2_Click(object sender, EventArgs e)


{


int timer1 = 0;


if (textBox1.Text != "")


timer1 = Convert.ToInt32(textBox1.Text) * 60;


Convert.ToString(timer1);


text2.Text = timer1;





}

What is wrong with this C# code?
It's because when you executed line "Convert.ToString(timer1)", you did not assign it to any string variable. Do this instead:





string text2Display = Convert.ToString(timer1);


text2.Text = text2Display;
Reply:that should be text2.Text = Convert.ToString(timer1)





You cannot change the actual type of timer1 at runtime but you can create a string which contains the textual representation of timer1. Convert.ToString returns a string which is the textual representation of the integer in timer1. And besides, the compiler has no idea what Convert.ToString actuall does( it just knows that its a function that takes in an int and returns a string), so it would have no way of knowing that timer1 should be turned into a string.

hamper

No comments:

Post a Comment