Pregunta

Tengo un TextBoxD1.Text y quiero convertirlo en un int para almacenarlo en una base de datos.

¿Cómo puedo hacer esto?

¿Fue útil?

Solución

Prueba esto:

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

o mejor aún:

int x = 0;

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

Además, desde Int32. TryParse devuelve un bool , puede usar su valor de retorno para tomar decisiones sobre los resultados del intento de análisis:

int x = 0;

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

Si tiene curiosidad, la diferencia entre Parse y TryParse se resume mejor así:

  

El método TryParse es como el Parse   método, excepto el método TryParse   no lanza una excepción si el   La conversión falla. Elimina el   necesita usar manejo de excepciones para probar   para una excepción de formato en el evento   eso es inválido y no puede ser   analizado correctamente - MSDN

Otros consejos

Convert.ToInt32( TextBoxD1.Text );

Use esto si está seguro de que el contenido del cuadro de texto es un int válido. Una opción más segura es

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

Esto le proporcionará un valor predeterminado que puede usar. Int32. TryParse también devuelve un valor booleano que indica si se pudo analizar o no, por lo que incluso puede usarlo como condición de una instrucción if .

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

No se lanzará si el texto no es numérico.

int myInt = int.Parse(TextBoxD1.Text)

Otra forma sería:

bool isConvertible = false;
int myInt = 0;

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

La diferencia entre los dos es que el primero arrojaría una excepción si el valor en su cuadro de texto no se puede convertir, mientras que el segundo simplemente devolvería falso.

Debe analizar la cadena y también debe asegurarse de que realmente esté en el formato de un entero.

La forma más fácil es 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);

La instrucción TryParse devuelve un valor booleano que representa si el análisis ha tenido éxito o no. Si tuvo éxito, el valor analizado se almacena en el segundo parámetro.

Ver Int32. TryParse Method (String, Int32) para obtener información más detallada.

Disfrútalo ...

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

Si bien ya hay muchas soluciones aquí que describen int.Parse , hay algo importante que falta en todas las respuestas. Por lo general, las representaciones de cadena de valores numéricos difieren según la cultura. Los elementos de cadenas numéricas como símbolos de moneda, separadores de grupo (o miles) y separadores decimales varían según la cultura.

Si desea crear una forma sólida de analizar una cadena a un entero, es importante tener en cuenta la información cultural. Si no lo hace, el se utilizará la configuración cultural actual . Eso podría dar al usuario una sorpresa bastante desagradable, o incluso peor, si está analizando formatos de archivo. Si solo desea analizar el inglés, lo mejor es hacerlo explícito, especificando la configuración de cultura que se utilizará:

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

Para obtener más información, lea CultureInfo, específicamente NumberFormatInfo en MSDN.

¡Tenga cuidado al usar Convert.ToInt32 () en un char!
¡Devolverá el UTF-16 Código del personaje!

Si accede a la cadena solo en una determinada posición utilizando el operador de indexación [i] , devolverá un char y no una cadena !

String input = "123678";

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

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

Puede escribir su propio método de extensión Y en cualquier parte del código simplemente llame

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

En este caso concreto

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

Como se explica en la documentación de TryParse , TryParse () devuelve un booleano que indica que se encontró un 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
}

Puedes usar cualquiera,

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

o

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

La conversión de string a int se puede hacer para: int , Int32 , Int64 y otros tipos de datos que reflejan tipos de datos enteros en .NET

El siguiente ejemplo muestra esta conversión:

Este elemento del adaptador de datos show (para información) se inicializó al valor int. Lo mismo se puede hacer directamente como,

int xxiiqVal = Int32.Parse(strNabcd);

Ej.

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

Enlace para ver esta demostración .

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

Esto haría

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

O puedes usar

int xi=Int32.Parse(x);

Consulte Red de desarrolladores de Microsoft para obtener más información

Puede convertir una cadena a int en C # usando:

Funciones de la clase de conversión, es decir, Convert.ToInt16 () , Convert.ToInt32 () , Convert.ToInt64 () o usando < code> Parse y TryParse Funciones. Se dan ejemplos aquí .

También puede usar un método de extensión , por lo que será más legible (aunque todo el mundo sea legible) ya está acostumbrado a las funciones regulares de Parse).

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

Y luego puedes llamarlo así:

  1. Si está seguro de que su cadena es un número entero, como " 50 " ;.

    int num = TextBoxD1.Text.ParseToInt32();
    
  2. Si no está seguro y desea evitar bloqueos.

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

Para hacerlo más dinámico, de modo que pueda analizarlo también para duplicar, flotar, etc., puede hacer una extensión genérica.

puedes hacer lo siguiente sin TryParse o funciones incorporadas

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

la forma en que siempre hago esto es así

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.
        }
    }
}

así es como lo haría, espero que esto ayude. (:

Puede convertir una cadena a un valor entero con la ayuda del método de análisis.

Por ejemplo:

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

Puedes probar esto, funcionará:

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

El valor de la cadena en la variable TextBoxD1.Text se convertirá en Int32 y se almacenará en x.

Si está buscando el camino largo, simplemente cree su ú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;
    }

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

Este código me funciona en Visual Studio 2010:

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

esto puede ayudarte; 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 bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top