Pergunta

Eu tenho um TextBoxD1.Text e eu quero convertê-lo em um int para armazená-lo em um banco de dados.

Como posso fazer isso?

Foi útil?

Solução

Tente isto:

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

ou melhor ainda:

int x = 0;

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

Além disso, como Int32.TryParse retorna um bool você pode usar seu retorno valor para decisões sobre a qualidade dos 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 TryParse é melhor resumido assim:

O método TryParse é como o Parse método, excepto o método TryParse não lançar uma exceção se o conversão falhar. Ele elimina a necessidade de exceção uso manipulação para teste para um FormatException no caso que s é inválido e não pode ser analisado com êxito. - MSDN

Outras dicas

Convert.ToInt32( TextBoxD1.Text );

Use isso se você se sentir confiante de que o conteúdo da caixa de texto é um int válido. A opção mais segura é

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

Este irá fornecer-lhe algum valor padrão que você pode usar. Int32.TryParse também retorna um valor booleano que indica se era capaz de analisar ou não, então você pode até usá-lo como a condição de uma instrução if.

if( Int32.TryParse( TextBoxD1.Text, out val ){
  DoSomething(..);
} else {
  HandleBadInput(..);
}
int.TryParse()

Ele não vai jogar se o texto não é numérico.

int myInt = int.Parse(TextBoxD1.Text)

Outra forma seria:

bool isConvertible = false;
int myInt = 0;

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

A diferença entre os dois é que o primeiro seria lançar uma exceção se o valor em sua caixa de texto não pode ser convertido, enquanto o segundo seria apenas retornar false.

Você precisa analisar a cadeia, e você também precisa se certificar de que é 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
}
int x = 0;
int.TryParse(TextBoxD1.Text, out x);

A declaração TryParse retorna um booleano representando se a análise foi bem sucedida ou não. Se ele conseguiu, o valor analisado é armazenado no segundo parâmetro.

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

Enjoy it ...

int i = 0;
string s = "123";
i =int.Parse(s);
i = Convert.ToInt32(s);

Enquanto já existem muitas soluções aqui que descrevem int.Parse, há algo importante faltando em todas as respostas. Normalmente, as representações de seqüência de valores numéricos diferem pela cultura. Elementos de cadeias numéricas tais como símbolos de moeda, grupo (ou milhares) separadores, e separadores decimais todos variar em cultura.

Se você quiser criar uma forma robusta para analisar uma string para um inteiro, é, portanto, importante ter as informações de cultura em conta. Se não o fizer, a configurações de cultura atual serão utilizados. Isso pode dar a um usuário uma surpresa bastante desagradável - ou, se você estiver formatos de arquivo de análise ainda piores. Se você quiser apenas Inglês análise, é melhor simplesmente torná-lo explícito, especificando as configurações de cultura para uso:

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-se sobre CultureInfo, especificamente NumberFormatInfo no MSDN.

Tenha cuidado ao usar Convert.ToInt32 () em um char!
Ele irá retornar a UTF-16 Código do caráter!

Se você acessar a corda só em uma determinada posição usando o operador [i] indexação ele 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

Você pode escrever seu próprio método 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 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();

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

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
}

Você pode usar qualquer um,

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

ou

int i =int.Parse(TextBoxD1.Text);

A conversão de string para int pode ser feito para: int, Int32, Int64 e outros tipos de dados que reflete os tipos de dados inteiro em .NET

A seguir exemplo mostra esta conversão:

Este show (para info) elemento adaptador de dados inicializada com 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 demonstração .

int x = Int32.TryParse(TextBoxD1.Text, out x)?x:0;
//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;
}

Esta faria

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

Ou você pode usar

int xi=Int32.Parse(x);

Consulte Microsoft Developer Network para mais informações

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

Funções da classe convertido ou seja Convert.ToInt16(), Convert.ToInt32(), Convert.ToInt64() ou usando Parse e TryParse Funções. Exemplos são dados aqui .

Você também pode usar um método de extensão , por isso vai ser mais legível (embora toda a gente é já utilizado para as funções Parse 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 então você pode chamá-lo dessa forma:

  1. Se você tem certeza que sua string é um número inteiro, como "50".

    int num = TextBoxD1.Text.ParseToInt32();
    
  2. Se você não tem certeza e quer evitar falhas.

    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 possa analisá-lo também para double, float, etc., você pode fazer uma extensão genérica.

você pode fazer como abaixo sem TryParse ou funções embutidas

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 i = Convert.ToInt32(TextBoxD1.Text);

do jeito que eu sempre faço isso é 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.
        }
    }
}

isto é como eu faria isso, eu espero que isso ajude. (:

Você pode converter string para um valor inteiro com a ajuda do método de análise.

Por exemplo:

int val = Int32.parse(stringToBeParsed);
int x = Int32.parse(1234);

Você pode tentar fazer isso, ele vai trabalhar:

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

O valor da cadeia no TextBoxD1.Text variável será convertido em Int32 e será armazenado em x.

Se você está procurando o caminho mais longo, basta criar o seu um 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;
    }

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");
}

Esse código funciona para mim no Visual Studio 2010:

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

isso pode ajudá-lo; 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.");
        }
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top