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 statment says if the string not a number display an error elce now you will have an intager.
}
}
}
int TheAnswer1 = 0;
bool Success = Int32.TryParse("42", out TheAnswer1);
if (!Success) {
Console.WriteLine("String not Convertable to an Integer");
}
METHOD 2
int TheAnswer2 = 0;
try {
TheAnswer2 = Int32.Parse("42");
}
catch {
Console.WriteLine("String not Convertable to an Integer");
}
METHOD 3
int TheAnswer3 = 0;
try {
TheAnswer3 = Int32.Parse("42");
}
catch (FormatException) {
Console.WriteLine("String not in the correct format for an Integer");
}
catch (ArgumentNullException) {
Console.WriteLine("String is null");
}
catch (OverflowException) {
Console.WriteLine("String represents a number less than"
+ "MinValue or greater than MaxValue");
}
Functions of convert class i.e. Convert.ToInt16(), Convert.ToInt32(), Convert.ToInt64() or by using Parse and TryParse Functions. Examples are given here.
the way i always do this is like this
this is how i would do it, i hope this helps. (:
METHOD 1
METHOD 2
METHOD 3
Conversion of
string
toint
can be done for:int
,Int32
,Int64
and other data types reflecting integer data types in .NETBelow example shows this conversion:
This show (for info) data adapter element initialized to int value. The same can be done directly like,
Ex.
Link to see this demo.
This code works for me in Visual Studio 2010:
You can convert a string to int in C# using:
Functions of convert class i.e.
Convert.ToInt16()
,Convert.ToInt32()
,Convert.ToInt64()
or by usingParse
andTryParse
Functions. Examples are given here.