11

I am taking a string value from a textbox named txtLastAppointmentNo and I want to convert it to an int and then store it in a database using Linq to sql but I am getting error "input string was not in proper format".

My input string is 2.

My code is:

      objnew.lastAppointmentNo=Convert.ToInt32(txtLastAppointmenNo.Text);

Please point out my mistake.

8
  • 2
    You need to show us the input string causing the error!
    – Gabe
    Jul 26, 2010 at 7:44
  • What value contains txtLastAppointmenNo? And may be you should provide to the Convert.ToInt32() txtLastAppointmenNo.Text ? Jul 26, 2010 at 7:44
  • i have written it .text in code but still there is problem..... this error Has made me crazy i dont know whats wrong. there.... :( Jul 26, 2010 at 8:01
  • 1
    Use the debugger to see what the value of txtLastAppointmentNo.Text actually is. I'm guessing it's not what you think it is - maybe an empty string. Jul 26, 2010 at 8:10
  • Do you have the dot in the string? ie. "2."? or just the 2, ie. "2"? Jul 28, 2010 at 9:18

3 Answers 3

14

Assuming you are using WebForms, then you just need to access the textbox value and not the textbox itself:

objnew.lastAppointmentNo = Convert.ToInt32(txtLastAppointmenNo.Text);

Or if you are referencing the HTML control then:

objnew.lastAppointmentNo = Convert.ToInt32(Request["txtLastAppointmenNo"]);
3
  • 2
    and would recommend some form of validation as well (e.g. Regex Validator)
    – StuartLC
    Jul 26, 2010 at 7:47
  • sorry i forget type in .Text here in Q. I have done it in code but still there is error. Jul 26, 2010 at 7:47
  • @nonnb +1 for that! @Nauman - Are you setting a breakpoint on that line of code and verifying the input? Jul 26, 2010 at 7:58
4

You can also go for int.Parse or int.TryParse or Convert.ToInt32

//int.Parse
int num = int.Parse(text);
//Convert.ToInt32
int num = Convert.ToInt32(text);

//int.TryParse
string text1 = "x";
        int num1;
        bool res = int.TryParse(text1, out num1);
        if (res == false)
        {
            // String is not a number.
        }
0

The answer for me was an empty string!

In objnew.lastAppointmentNo=Convert.ToInt32(txtLastAppointmenNo.Text);, txtLastAppointmenNo.Text was an empty value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.