我有一个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.
}
}
}
我就是这样做的。
其他回答
可以为int、Int32、Int64和其他反映.NET中整数数据类型的数据类型将字符串转换为int
以下示例显示了此转换:
这显示了初始化为int值的(for info)数据适配器元素。同样可以直接进行,
int xxiiqVal = Int32.Parse(strNabcd);
Ex.
string strNii = "";
UsrDataAdapter.SelectCommand.Parameters["@Nii"].Value = Int32.Parse(strNii );
链接以查看此演示。
如TryParse文档中所述,TryPars()返回一个布尔值,表示找到了一个有效的数字:
bool success = Int32.TryParse(TextBoxD1.Text, out val);
if (success)
{
// Put val in database
}
else
{
// Handle the case that the string doesn't contain a valid number
}
int myInt = int.Parse(TextBoxD1.Text)
另一种方式是:
bool isConvertible = false;
int myInt = 0;
isConvertible = int.TryParse(TextBoxD1.Text, out myInt);
两者之间的区别在于,如果无法转换文本框中的值,第一个将抛出异常,而第二个将返回false。
int x = Int32.TryParse(TextBoxD1.Text, out x) ? x : 0;
您也可以使用扩展方法,这样它会更可读(尽管每个人都已经习惯了常规的Parse函数)。
public static class StringExtensions
{
/// <summary>
/// Converts a string to int.
/// </summary>
/// <param name="value">The string to convert.</param>
/// <returns>The converted integer.</returns>
public static int ParseToInt32(this string value)
{
return int.Parse(value);
}
/// <summary>
/// Checks whether the value is integer.
/// </summary>
/// <param name="value">The string to check.</param>
/// <param name="result">The out int parameter.</param>
/// <returns>true if the value is an integer; otherwise, false.</returns>
public static bool TryParseToInt32(this string value, out int result)
{
return int.TryParse(value, out result);
}
}
然后你可以这样称呼它:
如果您确定字符串是整数,如“50”。int num=TextBoxD1.Text.ParseToInt32();如果您不确定并希望防止崩溃。整数;if(TextBoxD1.Text.TryParseToInt32(out num)){//解析成功,num具有解析的值。}
为了使其更动态,以便您也可以将其解析为double、float等,您可以创建一个通用扩展。