Domanda

Ho un TextBoxD1.Text e voglio convertirlo in un int per memorizzarlo in un database.

Come posso farlo?

È stato utile?

Soluzione

Prova questo:

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

o meglio ancora:

int x = 0;

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

Inoltre, poiché Int32. TryParse restituisce un bool che puoi usare il suo valore di ritorno per prendere decisioni sui risultati del tentativo di analisi:

int x = 0;

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

Se sei curioso, la differenza tra Parse e TryParse è meglio riassunta in questo modo:

  

Il metodo TryParse è come il Parse   metodo, ad eccezione del metodo TryParse   non genera un'eccezione se il   la conversione non riesce. Elimina il   è necessario utilizzare la gestione delle eccezioni per testare   per un FormatException nell'evento   quello s non è valido e non può essere   analizzato con successo. - MSDN

Altri suggerimenti

Convert.ToInt32( TextBoxD1.Text );

Usalo se sei sicuro che il contenuto della casella di testo sia un int valido. Un'opzione più sicura è

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

Questo ti fornirà un valore predefinito che puoi usare. Int32. TryParse restituisce anche un valore booleano che indica se è stato in grado di analizzare o meno, quindi puoi persino usarlo come condizione di un'istruzione if .

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

Non verrà generato se il testo non è numerico.

int myInt = int.Parse(TextBoxD1.Text)

Un altro modo sarebbe:

bool isConvertible = false;
int myInt = 0;

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

La differenza tra i due è che il primo genererebbe un'eccezione se il valore nella casella di testo non può essere convertito, mentre il secondo restituirà semplicemente false.

Devi analizzare la stringa e devi anche assicurarti che sia veramente nel formato di un numero intero.

Il modo più semplice è questo:

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

L'istruzione TryParse restituisce un valore booleano che indica se l'analisi ha avuto esito positivo o meno. Se ha esito positivo, il valore analizzato viene memorizzato nel secondo parametro.

Vedi Metodo Int32. TryParse (String, Int32) per informazioni più dettagliate.

Divertiti ...

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

Mentre ci sono già molte soluzioni qui che descrivono int.Parse , manca qualcosa di importante in tutte le risposte. In genere, le rappresentazioni di stringa di valori numerici differiscono per cultura. Gli elementi di stringhe numeriche come simboli di valuta, separatori di gruppi (o migliaia) e separatori decimali variano in base alla cultura.

Se si desidera creare un modo affidabile per analizzare una stringa in un numero intero, è quindi importante tenere conto delle informazioni sulla cultura. In caso contrario, verranno utilizzate le impostazioni della cultura corrente . Ciò potrebbe dare all'utente una brutta sorpresa, o peggio ancora, se stai analizzando i formati di file. Se vuoi solo analizzare l'inglese, è meglio renderlo esplicito, specificando le impostazioni della cultura da usare:

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

Per ulteriori informazioni, leggere su CultureInfo, in particolare NumberFormatInfo su MSDN.

Stai attento quando usi Convert.ToInt32 () su un carattere!
Restituirà il UTF-16 Codice del personaggio!

Se accedi alla stringa solo in una determinata posizione utilizzando l'operatore di indicizzazione [i] , verrà restituito un carattere e non una stringa !

String input = "123678";

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

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

Puoi scrivere il tuo metodo di estensione E ovunque nel codice basta chiamare

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

In questo 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

Come spiegato nella Documentazione TryParse , TryParse () restituisce un booleano che indica che è stato trovato un numero valido:

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
}

Puoi usare entrambi,

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

o

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

La conversione di stringa in int può essere effettuata per: int , Int32 , Int64 e altri tipi di dati che riflettono tipi di dati interi in .NET

L'esempio seguente mostra questa conversione:

Questo mostra (per informazioni) l'elemento dell'adattatore dati inizializzato sul valore int. Lo stesso può essere fatto direttamente come,

int xxiiqVal = Int32.Parse(strNabcd);

Ex.

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

Link per vedere questa demo .

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

Questo sarebbe

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

Oppure puoi usare

int xi=Int32.Parse(x);

Consultare Rete di sviluppatori Microsoft per ulteriori informazioni

Puoi convertire una stringa in int in C # usando:

Funzioni della classe convert, ad es. Convert.ToInt16 () , Convert.ToInt32 () , Convert.ToInt64 () o utilizzando < code> Parse e TryParse . Esempi sono riportati qui .

Puoi anche utilizzare un metodo di estensione , quindi sarà più leggibile (sebbene tutti lo siano già utilizzato per le normali funzioni 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);
    }
}

E poi puoi chiamarlo in questo modo:

  1. Se sei sicuro che la tua stringa sia un numero intero, come " 50 " ;.

    int num = TextBoxD1.Text.ParseToInt32();
    
  2. Se non si è sicuri e si desidera prevenire arresti anomali.

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

Per renderlo più dinamico, in modo da poterlo analizzare anche in double, float, ecc., puoi creare un'estensione generica.

puoi fare come di seguito senza TryParse o funzioni integrate

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

il modo in cui lo faccio sempre è così

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

ecco come lo farei, spero che questo aiuti. (:

È possibile convertire la stringa in un valore intero con l'aiuto del metodo di analisi.

Ad esempio:

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

Puoi provare questo, funzionerà:

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

Il valore di stringa nella variabile TextBoxD1.Text verrà convertito in Int32 e verrà archiviato in x.

Se stai cercando una strada lunga, crea il tuo unico metodo:

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

METODO 1

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

METODO 2

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

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

Questo codice funziona per me in Visual Studio 2010:

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

questo può aiutarti; 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.");
        }
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top