我有一个TextBoxD1.Text,我想将其转换为int,并将其存储在数据库中。
我该怎么做?
我有一个TextBoxD1.Text,我想将其转换为int,并将其存储在数据库中。
我该怎么做?
当前回答
我总是这样做:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace example_string_to_int
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
// This turns the text in text box 1 into a string
int b;
if (!int.TryParse(a, out b))
{
MessageBox.Show("This is not a number");
}
else
{
textBox2.Text = a+" is a number" ;
}
// Then this 'if' statement says if the string is not a number, display an error, else now you will have an integer.
}
}
}
我就是这样做的。
其他回答
对字符使用Convert.ToInt32()时要小心!它将返回字符的UTF-16代码!
如果使用[i]索引运算符仅在某个位置访问字符串,它将返回一个字符而不是字符串!
String input = "123678";
^
|
int indexOfSeven = 4;
int x = Convert.ToInt32(input[indexOfSeven]); // Returns 55
int x = Convert.ToInt32(input[indexOfSeven].toString()); // Returns 7
上面的所有答案都很好,但为了提供信息,我们可以使用int.TryParse,例如,它可以安全地将字符串转换为int
// TryParse returns true if the conversion succeeded
// and stores the result in j.
int j;
if (Int32.TryParse("-105", out j))
Console.WriteLine(j);
else
Console.WriteLine("String could not be parsed.");
// Output: -105
TryParse即使在无效输入和null时也不会抛出异常。在大多数程序上下文中,它总的来说比int.Parse更好。
来源:如何在C#中将字符串转换为int?(Int.Parse和Int.TryParse之间存在差异)
虽然我同意使用TryParse方法,但很多人不喜欢使用out参数(包括我自己)。在C#中添加了元组支持后,另一种方法是创建一个扩展方法,该方法将限制您使用单个实例的次数:
public static class StringExtensions
{
public static (int result, bool canParse) TryParse(this string s)
{
int res;
var valid = int.TryParse(s, out res);
return (result: res, canParse: valid);
}
}
(来源:C#如何将字符串转换为int)
您需要解析字符串,还需要确保它确实是整数格式。
最简单的方法是:
int parsedInt = 0;
if (int.TryParse(TextBoxD1.Text, out parsedInt))
{
// Code for if the string was valid
}
else
{
// Code for if the string was invalid
}
int.TryParse()
如果文本不是数字,它不会抛出。