ฉันมีTextBoxD1.Textและฉันต้องการแปลงเป็นintเพื่อจัดเก็บในฐานข้อมูล
ฉันจะทำสิ่งนี้ได้อย่างไร
ฉันมีTextBoxD1.Textและฉันต้องการแปลงเป็นintเพื่อจัดเก็บในฐานข้อมูล
ฉันจะทำสิ่งนี้ได้อย่างไร
คำตอบ:
ลองสิ่งนี้:
int x = Int32.Parse(TextBoxD1.Text);
หรือดีกว่า:
int x = 0;
Int32.TryParse(TextBoxD1.Text, out x);
นอกจากนี้เนื่องจากInt32.TryParseส่งคืน a boolคุณสามารถใช้ค่าส่งคืนเพื่อตัดสินใจเกี่ยวกับผลลัพธ์ของการแยกวิเคราะห์:
int x = 0;
if (Int32.TryParse(TextBoxD1.Text, out x))
{
    // you know that the parsing attempt
    // was successful
}
หากคุณอยากรู้อยากเห็นความแตกต่างระหว่างParseและTryParseสรุปได้ดีที่สุดเช่นนี้:
กระบวนการ TryParse วิธีนี้เหมือนกับวิธีการแยกวิเคราะห์ยกเว้นวิธี TryParse ไม่ได้เกิดข้อยกเว้นหากการแปลงล้มเหลว มันไม่จำเป็นต้องใช้การจัดการข้อยกเว้นเพื่อทดสอบ FormatException ในกรณีที่ s ไม่ถูกต้องและไม่สามารถแยกวิเคราะห์ได้สำเร็จ - MSDN
Int64.Parse()นี่ ถ้าใส่ไม่เป็น int แล้วคุณจะได้รับการ execption และกองติดตามด้วยInt64.ParseหรือบูลFalseด้วยดังนั้นคุณจะต้องมีถ้ามีคำสั่งเช่นInt64.TryParse() if (Int32.TryParse(TextBoxD1.Text, out x)) {}
                    Convert.ToInt32( TextBoxD1.Text );
intการใช้งานนี้ถ้าคุณรู้สึกมั่นใจว่าเนื้อหาของกล่องข้อความเป็นที่ถูกต้อง ตัวเลือกที่ปลอดภัยคือ
int val = 0;
Int32.TryParse( TextBoxD1.Text, out val );
สิ่งนี้จะให้ค่าเริ่มต้นที่คุณสามารถใช้ได้ Int32.TryParseส่งคืนค่าบูลีนที่ระบุว่าสามารถแยกวิเคราะห์ได้หรือไม่ดังนั้นคุณสามารถใช้เป็นเงื่อนไขของifคำสั่งได้
if( Int32.TryParse( TextBoxD1.Text, out val ){
  DoSomething(..);
} else {
  HandleBadInput(..);
}
              int myInt = int.Parse(TextBoxD1.Text)
อีกวิธีคือ:
bool isConvertible = false;
int myInt = 0;
isConvertible = int.TryParse(TextBoxD1.Text, out myInt);
ความแตกต่างระหว่างทั้งสองคือว่าสิ่งแรกที่จะโยนข้อยกเว้นถ้าค่าในกล่องข้อความของคุณไม่สามารถแปลงได้ในขณะที่คนที่สองจะกลับเท็จ
code  int NumericJL; บูล isNum = int.TryParse (nomeeJobBand ออก NumericJL); if (isNum) // The JL ที่ได้รับการรับรองสามารถ pasred ไปยัง int แล้วดำเนินการต่อเพื่อเปรียบเทียบ {if (! (NumericJL> = 6)) {// Nominate} // else {}}
                    คุณต้องแยกสตริงและคุณต้องให้แน่ใจว่ามันอยู่ในรูปแบบของจำนวนเต็มอย่างแท้จริง
วิธีที่ง่ายที่สุดคือ:
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
}
              ระวังเมื่อใช้ Convert.ToInt32 () กับตัวอักษร! 
มันจะส่งคืนรหัสUTF-16ของตัวละคร!
หากคุณเข้าถึงสตริงเฉพาะในตำแหน่งใดตำแหน่งหนึ่งที่ใช้[i]ประกอบการจัดทำดัชนีก็จะกลับมาcharและไม่ได้string!
String input = "123678";
                    ^
                    |
int indexOfSeven =  4;
int x = Convert.ToInt32(input[indexOfSeven]);             // Returns 55
int x = Convert.ToInt32(input[indexOfSeven].toString());  // Returns 7
              int x = 0;
int.TryParse(TextBoxD1.Text, out x);
คำสั่ง TryParse ส่งคืนบูลีนที่แสดงว่าการแยกวิเคราะห์สำเร็จหรือไม่ หากประสบความสำเร็จค่าการแยกวิเคราะห์จะถูกเก็บไว้ในพารามิเตอร์ที่สอง
ดูที่Int32.TryParse วิธี (String, Int32)สำหรับข้อมูลรายละเอียดเพิ่มเติม
สนุกกับมัน...
int i = 0;
string s = "123";
i =int.Parse(s);
i = Convert.ToInt32(s);
              ในขณะที่มีint.Parseคำตอบหลายคำตอบอยู่ตรงนี้ แต่ก็มีบางสิ่งที่ขาดหายไปในคำตอบทั้งหมด โดยทั่วไปแล้วการแทนค่าสตริงของค่าตัวเลขแตกต่างกันตามวัฒนธรรม องค์ประกอบของสตริงตัวเลขเช่นสัญลักษณ์สกุลเงินตัวแยกกลุ่ม (หรือหลายพัน) และตัวคั่นทศนิยมทั้งหมดจะแตกต่างกันไปตามวัฒนธรรม
หากคุณต้องการสร้างวิธีที่มีประสิทธิภาพในการวิเคราะห์สตริงเป็นจำนวนเต็มดังนั้นจึงเป็นสิ่งสำคัญที่จะต้องคำนึงถึงข้อมูลวัฒนธรรม ถ้าคุณทำไม่ได้การตั้งค่าวัฒนธรรมปัจจุบันจะถูกนำมาใช้ นั่นอาจทำให้ผู้ใช้รู้สึกประหลาดใจที่น่ารังเกียจ - หรือแย่กว่านั้นคือหากคุณแยกวิเคราะห์รูปแบบไฟล์ หากคุณต้องการแยกวิเคราะห์ภาษาอังกฤษเป็นการดีที่สุดที่จะให้ชัดเจนโดยระบุการตั้งค่าวัฒนธรรมที่จะใช้:
var culture = CultureInfo.GetCulture("en-US");
int result = 0;
if (int.TryParse(myString, NumberStyles.Integer, culture, out result))
{
    // use result...
}
สำหรับข้อมูลเพิ่มเติมอ่านได้ที่ CultureInfo โดยเฉพาะNumberFormatInfoบน MSDN
คุณสามารถเขียนวิธีการขยายของคุณเอง
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();
    }
}
และทุกที่ในรหัสเพียงแค่โทร
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
ในกรณีที่เป็นรูปธรรมนี้
int yourValue = TextBoxD1.Text.ParseInt();
              StringExtensionsแทนIntegerExtensionsเนื่องจากวิธีการขยายเหล่านี้ทำงานบนstringและไม่ใช่บนint?
                    ดังที่อธิบายไว้ในเอกสารประกอบ TryParseแล้ว TryParse () จะส่งคืน Boolean ซึ่งระบุว่าพบหมายเลขที่ถูกต้อง:
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
}
              คุณสามารถใช้อย่างใดอย่างหนึ่ง
int i = Convert.ToInt32(TextBoxD1.Text);
หรือ
int i = int.Parse(TextBoxD1.Text);
              //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;
}
              คุณสามารถแปลงสตริงเป็น int ใน C # โดยใช้:
ฟังก์ชั่นของการแปลงระดับคือConvert.ToInt16(), Convert.ToInt32(), Convert.ToInt64()หรือโดยการใช้ParseและTryParseฟังก์ชั่น ตัวอย่างจะได้รับที่นี่
คุณอาจใช้วิธีการขยายดังนั้นมันจะสามารถอ่านได้มากขึ้น (แม้ว่าทุกคนจะคุ้นเคยกับฟังก์ชั่นการแจงทั่วไปอยู่แล้ว)
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);
    }
}
จากนั้นคุณสามารถเรียกมันว่า:
หากคุณแน่ใจว่าสตริงของคุณเป็นจำนวนเต็มเช่น "50"
int num = TextBoxD1.Text.ParseToInt32();หากคุณไม่แน่ใจและต้องการป้องกันการล่ม
int num;
if (TextBoxD1.Text.TryParseToInt32(out num))
{
    //The parse was successful, the num has the parsed value.
}หากต้องการทำให้มีไดนามิกมากขึ้นคุณสามารถแยกเป็นสองเท่าลอยเป็นต้นคุณสามารถสร้างส่วนขยายทั่วไปได้
การแปลงสภาพstringที่จะintสามารถทำได้: int, Int32, Int64และประเภทข้อมูลอื่น ๆ ที่สะท้อนให้เห็นถึงจำนวนเต็มชนิดข้อมูลใน .NET
ตัวอย่างด้านล่างแสดงการแปลงนี้:
องค์ประกอบอะแดปเตอร์ข้อมูลการแสดง (สำหรับข้อมูล) นี้เริ่มต้นเป็นค่า int เช่นเดียวกันสามารถทำได้โดยตรงเช่น
int xxiiqVal = Int32.Parse(strNabcd);
อดีต
string strNii = "";
UsrDataAdapter.SelectCommand.Parameters["@Nii"].Value = Int32.Parse(strNii );
              สิ่งนี้จะทำ
string x = TextBoxD1.Text;
int xi = Convert.ToInt32(x);
หรือคุณสามารถใช้
int xi = Int32.Parse(x);
              คุณสามารถทำเหมือนด้านล่างโดยไม่ต้องใช้ฟังก์ชัน TryParse หรือ 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;
}
              int i = Convert.ToInt32(TextBoxD1.Text);
              คุณสามารถแปลงสตริงเป็นค่าจำนวนเต็มด้วยวิธีการวิเคราะห์คำ
เช่น:
int val = Int32.parse(stringToBeParsed);
int x = Int32.parse(1234);
              วิธีที่ฉันทำเช่นนี้เป็นประจำ:
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' statement says if the string is not a number, display an error, else now you will have an integer.
        }
    }
}
นี่คือวิธีที่ฉันจะทำมัน
หากคุณกำลังมองหาทางที่ไกลเพียงแค่สร้างวิธีการของคุณ:
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;
    }
              วิธีที่ 1
int  TheAnswer1 = 0;
bool Success = Int32.TryParse("42", out TheAnswer1);
if (!Success) {
    Console.WriteLine("String not Convertable to an Integer");
}
วิธีที่ 2
int TheAnswer2 = 0;
try {
    TheAnswer2 = Int32.Parse("42");
}
catch {
    Console.WriteLine("String not Convertable to an Integer");
}
วิธีที่ 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");
}
              รหัสนี้ใช้ได้กับฉันใน Visual Studio 2010:
int someValue = Convert.ToInt32(TextBoxD1.Text);
              สิ่งนี้ใช้ได้กับฉัน:
using System;
namespace numberConvert
{
    class Program
    {
        static void Main(string[] args)
        {
            string numberAsString = "8";
            int numberAsInt = int.Parse(numberAsString);
        }
    }
}
              คุณสามารถลองต่อไปนี้ มันจะทำงาน:
int x = Convert.ToInt32(TextBoxD1.Text);
ค่าสตริงในตัวแปร TextBoxD1.Text จะถูกแปลงเป็น Int32 และจะถูกเก็บไว้ใน x
ใน C # v.7 คุณสามารถใช้พารามิเตอร์ inline out โดยไม่มีการประกาศตัวแปรเพิ่มเติม:
int.TryParse(TextBoxD1.Text, out int x);
              outพารามิเตอร์ไม่สนับสนุนใน C # ตอนนี้หรือไม่
                    สิ่งนี้อาจช่วยคุณได้ 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.");
        }
    }
}