Nauman.Khattak
Nauman.Khattak

Reputation: 641

How do I convert a string to an int type in C#?

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.

Upvotes: 11

Views: 49382

Answers (3)

Thomas Collier
Thomas Collier

Reputation: 1

The answer for me was an empty string!

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

Upvotes: 0

Pranay Rana
Pranay Rana

Reputation: 176896

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.
        }

Upvotes: 4

Dustin Laine
Dustin Laine

Reputation: 38503

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"]);

Upvotes: 14

Related Questions