Click here to Skip to main content
15,909,091 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Not sure what is going on here.
I get an exception on the conversion of the string to int.

using System;
using System.Windows.Forms;

namespace WinFormsApp4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            int anInteger = Convert.ToInt32(textBox1.Text);
            label1.Text = anInteger.ToString();
        }
    }
}

Is me or my Visual Studio is crazy?!
Posted
Updated 22-Dec-13 2:59am
v2
Comments
Er. Tushar Srivastava 22-Dec-13 8:54am    
Is there any text inside the textbox when the application is loaded?
Millone 22-Dec-13 8:57am    
no. It is empty but even if I set the text box ="1"; I get the same problem.
Er. Tushar Srivastava 22-Dec-13 9:01am    
Try to do this, add a form load event and shift this statement to that part I guess that will solve the issue. BTW, i am no expert in this... yet, try it please :)
Pheonyx 22-Dec-13 8:55am    
Okay, well the first question is what exception are you getting? You've not told use that.
The next question, is why on earth are you converting a string to make it a string again it seems like a bit of wasted time?
Millone 22-Dec-13 8:58am    
Format exception not managed on this line int anInteger = Convert.ToInt32(textBox1.Text);

1 solution

Firstly, don't use Convert.ToInt32 - use the TryParse method instead:
C#
int myInt = 0;
if (!int.TryParse(textBox1.Text, out myInt))
   {
   MessageBox.Show("Please enter a number!");
   return;
   }
label1.Text = myInt.ToString();
It returns true if the conversion succeeded, and false if it didn't.

But... there is a slightly deeper problem.
Why are you doing this in the constructor? The value is whatever you set at desgin time, so you really shouldn't need to read it yet...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900