我有一个TextBoxD1.Text,我想将其转换为int,并将其存储在数据库中。
我该怎么做?
我有一个TextBoxD1.Text,我想将其转换为int,并将其存储在数据库中。
我该怎么做?
当前回答
享受它。。。
int i = 0;
string s = "123";
i =int.Parse(s);
i = Convert.ToInt32(s);
其他回答
如果您知道字符串是整数,请执行以下操作:
int value = int.Parse(TextBoxD1.Text);
如果您不知道字符串是整数,请使用TryParse安全地执行。
在C#7.0中,可以使用内联变量声明。
如果解析成功-value=其解析值。如果解析失败-值=0。
代码:
if (int.TryParse(TextBoxD1.Text, out int value))
{
// Parse succeed
}
缺点:
无法区分0值和未分析的值。
我总是这样做:
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.
}
}
}
我就是这样做的。
如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 x = Int32.Parse(TextBoxD1.Text);
或者更好:
int x = 0;
Int32.TryParse(TextBoxD1.Text, out x);
此外,由于Int32.TryParse返回bool,您可以使用其返回值来决定解析尝试的结果:
int x = 0;
if (Int32.TryParse(TextBoxD1.Text, out x))
{
// you know that the parsing attempt
// was successful
}
如果你很好奇,Parse和TryParse之间的区别最好总结如下:
TryParse方法类似于Parse方法,TryParse方法除外如果转换失败。它消除了需要使用异常处理来测试事件中的FormatExceptions无效,不能已成功解析。-世界末日
Convert.ToInt32( TextBoxD1.Text );
如果您确信文本框的内容是有效的int,请使用此选项
int val = 0;
Int32.TryParse( TextBoxD1.Text, out val );
这将为您提供一些可以使用的默认值。Int32.TryParse还返回一个布尔值,指示它是否能够解析,因此您甚至可以将其用作if语句的条件。
if( Int32.TryParse( TextBoxD1.Text, out val ){
DoSomething(..);
} else {
HandleBadInput(..);
}