C#textBox字符串类型->整数类型 [英] C# textBox String type -> integer type

查看:207
本文介绍了C#textBox字符串类型->整数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String t = textBox1.Text;
         int a = int.Parse(t);
         if( a < 24)
         {
             MessageBox.Show("24 over.");
             textBox1.Clear();
         }

"System.FormatException"类型的未处理异常发生在 mscorlib.dll附加信息:输入字符串不正确 格式

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?

推荐答案

简短答案,请使用Binding

对于构建示例,我将假设您尚未指定Winforms,但是如果它是WPF,请更正我.无论如何,基本原理是完全一样的.

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.

这篇关于C#textBox字符串类型-&gt;整数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆