问题
String t = textBox1.Text;
int a = int.Parse(t);
if( a < 24)
{
MessageBox.Show("24 over.");
textBox1.Clear();
}
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll Additional information: Input string was not in a correct format
How can I change String type value to integer type value?
回答1:
t
must be a string that's parseable to an integer. According to the runtime, it isn't.
You can make the code a bit more resilient by using TryParse
instead. Something like this:
int a = 0;
if (!int.TryParse(t, out a))
{
// input wasn't parseable to an integer, show a message perhaps?
}
// continue with your logic
回答2:
Short answer, use Binding
For building the example I'm going to assume Winforms as you haven't specified, but correct me if it's WPF instead. The basic principle is exactly the same anyway.
The idea is to bind a property to the control text, that will receive the parsed number directly from the control. Validation of correctness will be done by the binding engine and visual clues will be given in case of errors, and that property can the used safely in any further code.
An example implementation could be something like this:
//Declare property that will hold the converted value
public int TextBoxValue { get; set; }
protected override void OnLoad()
{
//Initialize databinding from the control Text property to this form TextBoxValue property
this.Textbox1.DataBindings.Add("Text",this,"TextBoxValue");
}
private void Button1_Click(object sender, EventArgs e)
{
//This is an example of usage of the bound data, analogous to your original code
//Data is read directly from the property
if(this.TextBoxValue < 24)
{
MessageBox.Show("24 over.");
//To move changes back, simply set the property and raise a PropertyChanged event to signal binding to update
this.TextBoxValue = 0;
this.PropertyChanged(this,new PropertyChangedEventArgs("TextBoxValue"));
}
}
//Declare event for informing changes on bound properties, make sure the form implements INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
That is, the code uses the property instead of the control directly, while the binding takes care of the conversions in between.
来源:https://stackoverflow.com/questions/28665450/c-sharp-textbox-string-type-integer-type