我有一个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值和未分析的值。
您可以在没有TryParse或内置函数的情况下执行以下操作:
static int convertToInt(string a)
{
int x = 0;
for (int i = 0; i < a.Length; i++)
{
int temp = a[i] - '0';
if (temp != 0)
{
x += temp * (int)Math.Pow(10, (a.Length - (i+1)));
}
}
return x;
}
int.TryParse()
如果文本不是数字,它不会抛出。
我总是这样做:
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 parsedInt = 0;
if (int.TryParse(TextBoxD1.Text, out parsedInt))
{
// Code for if the string was valid
}
else
{
// Code for if the string was invalid
}