如何在C#中将字符串转换为int类型?

时间:2022-09-02 09:16:53

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

我从一个名为txtLastAppointmentNo的文本框中获取字符串值,我想将其转换为int,然后使用Linq to sql将其存储在数据库中,但是我收到错误“输入字符串格式不正确”。

My input string is 2.

我的输入字符串是2。

My code is:

我的代码是:

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

Please point out my mistake.

请指出我的错误。

3 个解决方案

#1


14  

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

假设您使用的是WebForms,那么您只需要访问文本框值而不是文本框本身:

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

Or if you are referencing the HTML control then:

或者,如果您正在引用HTML控件,那么:

objnew.lastAppointmentNo = Convert.ToInt32(Request["txtLastAppointmenNo"]);

#2


4  

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

你也可以去int.Parse或int.TryParse或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.
        }

#3


0  

The answer for me was an empty string!

我的答案是一个空字符串!

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

在objnew.lastAppointmentNo = Convert.ToInt32(txtLastAppointmenNo.Text);, txtLastAppointmenNo.Text是一个空值。

#1


14  

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

假设您使用的是WebForms,那么您只需要访问文本框值而不是文本框本身:

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

Or if you are referencing the HTML control then:

或者,如果您正在引用HTML控件,那么:

objnew.lastAppointmentNo = Convert.ToInt32(Request["txtLastAppointmenNo"]);

#2


4  

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

你也可以去int.Parse或int.TryParse或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.
        }

#3


0  

The answer for me was an empty string!

我的答案是一个空字符串!

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

在objnew.lastAppointmentNo = Convert.ToInt32(txtLastAppointmenNo.Text);, txtLastAppointmenNo.Text是一个空值。