I have a TextBoxD1.Text
and I want to convert it to an int
to store it in a database.
How can I do this?
While there are already many solutions here that describe int.Parse
, there's something important missing in all the answers. Typically, the string representations of numeric values differ by culture. Elements of numeric strings such as currency symbols, group (or thousands) separators, and decimal separators all vary by culture.
If you want to create a robust way to parse a string to an integer, it's therefore important to take the culture information into account. If you don't, the current culture settings will be used. That might give a user a pretty nasty surprise -- or even worse, if you're parsing file formats. If you just want English parsing, it's best to simply make it explicit, by specifying the culture settings to use:
var culture = CultureInfo.GetCulture("en-US");
int result = 0;
if (int.TryParse(myString, NumberStyles.Integer, culture, out result))
{
// use result...
}
For more information, read up on CultureInfo, specifically NumberFormatInfo on MSDN.
You can convert string to an integer value with the help of parse method.
Eg:
int val = Int32.parse(stringToBeParsed);
int x = Int32.parse(1234);
The way I always do this is like this:
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.
}
}
}
This is how I would do it.
As explained in the TryParse documentation, TryParse() returns a Boolean which indicates that a valid number was found:
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 i = Convert.ToInt32(TextBoxD1.Text);
This works for me:
using System;
namespace numberConvert
{
class Program
{
static void Main(string[] args)
{
string numberAsString = "8";
int numberAsInt = int.Parse(numberAsString);
}
}
}