Como posso converter String para Int?

tenho um {[[0]} e quero convertê-lo para um int para o guardar numa base de dados.

Como posso fazer isto?

Author: stefanobaghino, 2009-06-20

27 answers

Tenta isto:

int x = Int32.Parse(TextBoxD1.Text);

Ou melhor ainda:

int x = 0;

Int32.TryParse(TextBoxD1.Text, out x);

Também, uma vez que Int32.TryParse devolve um bool poderá usar o seu valor de retorno para tomar decisões sobre os resultados da tentativa de análise:

int x = 0;

if (Int32.TryParse(TextBoxD1.Text, out x))
{
    // you know that the parsing attempt
    // was successful
}

Se você está curioso, a diferença entre Parse e {[6] } é melhor resumida assim:

O método de TryParse é como o Parse método, excepto o método TryParse não abre uma excepção se o a conversão falha. Elimina o necessidade de utilizar tratamento das excepções ao ensaio for a FormatException in the event isso é inválido e não pode ser foi processada com sucesso. - MSDN

 763
Author: Andrew Hare, 2016-07-20 20:49:31
Convert.ToInt32( TextBoxD1.Text );

Utilize isto se estiver confiante de que o conteúdo da caixa de texto é um int válido. Uma opção mais segura é

int val = 0;
Int32.TryParse( TextBoxD1.Text, out val );

Isto dar-lhe-á algum valor predefinido que possa usar. {[3] } também devolve um valor booleano indicando se ele foi capaz de processar ou não, por isso pode até usá-lo como condição de uma declaração if.

if( Int32.TryParse( TextBoxD1.Text, out val ){
  DoSomething(..);
} else {
  HandleBadInput(..);
}
 40
Author: Babak Naffas, 2017-10-23 17:52:05
int.TryParse()

Não lança se o texto não for numérico.

 27
Author: n8wrl, 2011-04-03 18:00:27
int myInt = int.Parse(TextBoxD1.Text)
Outra maneira seria:
bool isConvertible = false;
int myInt = 0;

isConvertible = int.TryParse(TextBoxD1.Text, out myInt);

A diferença entre os dois é que o primeiro abriria uma excepção se o valor na sua caixa de texto não pudesse ser convertido, enquanto o segundo apenas retornaria falso.

 17
Author: Andre Kraemer, 2014-05-26 08:52:08

Você precisa processar a string, e você também precisa garantir que ela está realmente no formato de um inteiro.

A maneira mais fácil é esta:

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
}
 15
Author: Jacob, 2009-06-19 20:06:36
int x = 0;
int.TryParse(TextBoxD1.Text, out x);

A declaração de TryParse devolve um booleano que representa se o processamento foi bem sucedido ou não. Se tiver sucesso, o valor processado é armazenado no segundo parâmetro.

Ver Int32.Método de TryParse (String, Int32) para informações mais detalhadas.

 10
Author: jorelli, 2014-05-26 08:53:37
Aproveita...
int i = 0;
string s = "123";
i =int.Parse(s);
i = Convert.ToInt32(s);
 8
Author: Salim Latif Waigaonkar, 2016-08-16 18:05:21

Tal como explicado na documentação TryParse , o TryParse () devolve um booleano que indica que foi encontrado um número válido:

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
}
 6
Author: JeffH, 2009-06-19 20:10:41
Embora já existam muitas soluções aqui que descrevem int.Parse, há algo importante faltando em todas as respostas. Tipicamente, as representações de cadeias de valores numéricos diferem por cultura. Elementos de cadeias numéricas, tais como símbolos de moeda, separadores de grupo (ou milhares), e separadores decimais, todos variam de acordo com a cultura.

Se você quer criar uma maneira robusta de processar uma string para um inteiro, é portanto importante levar a informação da cultura em conta. Se não, serão usadas as configurações atuais de cultura . Isso pode dar a um usuário uma surpresa muito desagradável -- ou ainda pior, se você estiver analisando formatos de arquivos. Se você só quer análise em inglês, é melhor simplesmente torná-lo explícito, especificando as configurações de cultura a usar:

var culture = CultureInfo.GetCulture("en-US");
int result = 0;
if (int.TryParse(myString, NumberStyles.Integer, culture, out result))
{
    // use result...
}

Para mais informações, leia sobre CultureInfo, especificamente Number Formatinfo sobre MSDN.

 6
Author: atlaste, 2015-07-06 11:33:17

Tenha cuidado ao usar o Convert.ToInt32 () on a char!
Ele irá devolver o código de UTF-16 do personagem!

Se você acessar o texto apenas em uma determinada posição usando o operador de indexação [i] ele irá retornar um char e não um string!

String input = "123678";

int x = Convert.ToInt32(input[4]);  // returns 55

int x = Convert.ToInt32(input[4].toString());  // returns 7
 6
Author: Mong Zhu, 2018-07-30 07:39:37

Você pode escrever o seu próprio método de extesion

public static class IntegerExtensions
{
    public static int ParseInt(this string value, int defaultValue = 0)
    {
        int parsedValue;
        if (int.TryParse(value, out parsedValue))
        {
            return parsedValue;
        }

        return defaultValue;
    }

    public static int? ParseNullableInt(this string value)
    {
        if (string.IsNullOrEmpty(value))
        {
            return null;
        }

        return value.ParseInt();
    }
}

E onde quer que em código apenas chamar

int myNumber = someString.ParseInt(); // returns value or 0
int age = someString.ParseInt(18); // with default value 18
int? userId = someString.ParseNullableInt(); // returns value or null

Neste caso concreto

int yourValue = TextBoxD1.Text.ParseInt();
 5
Author: Miroslav Holec, 2016-12-17 15:31:13

Pode usar qualquer um deles,

int i = Convert.ToInt32(TextBoxD1.Text);

Ou

int i =int.Parse(TextBoxD1.Text);
 4
Author: Deadlock, 2016-08-16 18:05:38

Você também pode usar um método de extensão , por isso será mais legível (embora todos já estejam habituados às funções de processamento regulares).

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);
    }
}
E depois podes chamar-lhe assim:
  1. Se tens a certeza que a tua corda é um inteiro, como "50".

    int num = TextBoxD1.Text.ParseToInt32();
    
  2. Se não tiver a certeza e quiser evitar acidentes.

    int num;
    if (TextBoxD1.Text.TryParseToInt32(out num))
    {
        //The parse was successful, the num has the parsed value.
    }
    

Para torná-lo mais dinâmico, para que você possa analisá-lo também para dobrar, flutuar, etc., você pode fazer um extensão genérica.

 3
Author: Misha Zaslavsky, 2014-05-26 09:00:45

A conversão de string para int pode ser feita por: int, Int32, Int64 e outros tipos de dados que reflectem tipos de dados inteiros em. Net

Abaixo do exemplo mostra esta conversão:

Isto mostra (para info) o elemento Adaptador de dados inicializado para o valor int. O mesmo pode ser feito diretamente como,

int xxiiqVal = Int32.Parse(strNabcd);

Ex.

string strNii = "";
UsrDataAdapter.SelectCommand.Parameters["@Nii"].Value = Int32.Parse(strNii );

Link para ver esta demo .

 3
Author: Edwin b, 2016-07-27 09:23:17
//May be quite some time ago but I just want throw in some line for any one who may still need it

int intValue;
string strValue = "2021";

try
{
    intValue = Convert.ToInt32(strValue);
}
catch
{
    //Default Value if conversion fails OR return specified error
    // Example 
    intValue = 2000;
}
 3
Author: Jsprings, 2017-02-27 07:47:29

Isto faria

string x=TextBoxD1.Text;
int xi=Convert.ToInt32(x);

Ou pode utilizar

int xi=Int32.Parse(x);

Ver Microsoft Developer Network para mais informações

 3
Author: Tony Stark, 2017-07-03 06:27:19

Você pode converter uma cadeia para int em C# usando:

Funções da classe convert i.e. Convert.ToInt16(), Convert.ToInt32(), Convert.ToInt64() ou usando as funções Parse e TryParse. São dados exemplos aqui .

 3
Author: Atif, 2018-05-11 06:19:32
int i = Convert.ToInt32(TextBoxD1.Text);
 2
Author: deepu, 2011-04-03 17:59:59
A forma como faço sempre isto é assim.
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.
        }
    }
}
É assim que eu o faria, espero que ajude. (:
 2
Author: Isaac Newton, 2016-04-20 15:42:47
int x = Int32.TryParse(TextBoxD1.Text, out x)?x:0;
 2
Author: Mohammad Rahman, 2017-01-27 21:42:31

Pode fazer como em baixo sem funções de TryParse ou inbuilt

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 ;
}
 2
Author: lazydeveloper, 2018-04-11 18:11:33
Pode tentar, vai funcionar.
int x = Convert.ToInt32(TextBoxD1.Text);

O valor do texto na variável TextBoxD1.O texto será convertido em Int32 e será armazenado em X.

 0
Author: Kartikey Kushwaha, 2015-07-06 11:17:10
Se está à procura do caminho mais longo, basta criar o seu único método:
static int convertToInt(string a)
    {
        int x = 0;

        Char[] charArray = a.ToCharArray();
        int j = charArray.Length;

        for (int i = 0; i < charArray.Length; i++)
        {
            j--;
            int s = (int)Math.Pow(10, j);

            x += ((int)Char.GetNumericValue(charArray[i]) * s);
        }
        return x;
    }
 0
Author: jul taps, 2017-06-05 12:41:14

Método 1

int  TheAnswer1 = 0;
bool Success = Int32.TryParse("42", out TheAnswer1);
if (!Success) {
    Console.WriteLine("String not Convertable to an Integer");
}

Método 2

int TheAnswer2 = 0;
try {
    TheAnswer2 = Int32.Parse("42");
}
catch {
    Console.WriteLine("String not Convertable to an Integer");
}

Método 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");
}
 0
Author: Bill Moore, 2017-10-18 12:46:28
Este código funciona para mim no Visual Studio 2010.
int someValue = Convert.ToInt32(TextBoxD1.Text);
 0
Author: Sarib Shamim, 2018-01-02 12:10:01

A maneira mais simples é usar um auxiliar de extensão como este:

public static class StrExtensions
{
  public static int ToInt(this string s, int defVal = 0) => int.TryParse(s, out var v) ? v : defVal;
  public static int? ToNullableInt(this string s, int? defVal = null) => int.TryParse(s, out var v) ? v : defVal;
}

A utilização é tão simples:

var x = "123".ToInt(); // 123
var y = "abc".ToInt(); // 0

string t = null;
var z = t.ToInt(-1); // -1
var w = "abc".ToNullableInt(); // null
 0
Author: S.Serpooshan, 2018-08-01 11:14:56

Isto pode ajudar-te; d

{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        float Stukprijs;
        float Aantal;
        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            MessageBox.Show("In de eersre textbox staat een geldbedrag." + Environment.NewLine + "In de tweede textbox staat een aantal." + Environment.NewLine + "Bereken wat er moetworden betaald." + Environment.NewLine + "Je krijgt 15% korting over het bedrag BOVEN de 100." + Environment.NewLine + "Als de korting meer dan 10 euri is," + Environment.NewLine + "wordt de korting textbox lichtgroen");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            errorProvider2.Clear();
            if (float.TryParse(textBox1.Text, out Stukprijs))
            {
                if (float.TryParse(textBox2.Text, out Aantal))
                {
                    float Totaal = Stukprijs * Aantal;
                    string Output = Totaal.ToString();
                    textBox3.Text = Output;
                    if (Totaal >= 100)
                    {
                        float korting = Totaal - 100;
                        float korting2 = korting / 100 * 15;
                        string Output2 = korting2.ToString();
                        textBox4.Text = Output2;
                        if (korting2 >= 10)
                        {
                            textBox4.BackColor = Color.LightGreen;
                        }
                        else
                        {
                            textBox4.BackColor = SystemColors.Control;
                        }
                    }
                    else
                    {
                        textBox4.Text = "0";
                        textBox4.BackColor = SystemColors.Control;
                    }
                }
                else
                {
                    errorProvider2.SetError(textBox2, "Aantal plz!");
                }

            }
            else
            {
                errorProvider1.SetError(textBox1, "Bedrag plz!");
                if (float.TryParse(textBox2.Text, out Aantal))
                {

                }
                else
                {
                    errorProvider2.SetError(textBox2, "Aantal plz!");
                }
            }

        }

        private void BTNwissel_Click(object sender, EventArgs e)
        {
            //LL, LU, LR, LD.
            Color c = LL.BackColor;
            LL.BackColor = LU.BackColor;
            LU.BackColor = LR.BackColor;
            LR.BackColor = LD.BackColor;
            LD.BackColor = c;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            MessageBox.Show("zorg dat de kleuren linksom wisselen als je op de knop drukt.");
        }
    }
}
 -3
Author: jan koekepan, 2017-01-27 21:42:51