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}
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();
If you are not sure and want to prevent crashes.
int num;if (TextBoxD1.Text.TryParseToInt32(out num)){//The parse was successful, the num has the parsed value.}
To make it more dynamic, so you can parse it also to double, float, etc., you can make a generic extension.
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 0int age = someString.ParseInt(18); // With default value 18int? userId = someString.ParseNullableInt(); // Returns value or null
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 stringint 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.}}}
//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// ExampleintValue = 2000;}
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;}
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");}
// TryParse returns true if the conversion succeeded// and stores the result in j.int j;if (Int32.TryParse("-105", out j))Console.WriteLine(j);elseConsole.WriteLine("String could not be parsed.");// Output: -105