【问题标题】:C# textBox String type -> integer typeC# textBox 字符串类型 -> 整数类型
【发布时间】:2015-02-23 00:57:19
【问题描述】:
String t = textBox1.Text;
         int a = int.Parse(t);
         if( a < 24)
         {
             MessageBox.Show("24 over.");
             textBox1.Clear();
         }

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

如何将String类型的值改为整数类型的值?

【问题讨论】:

  • 你的 textBox1.Text 里有什么?
  • textBox1只是输入数字。
  • 好的,但是当你运行你的代码时它包含什么?

标签: formatexception


【解决方案1】:

t 必须是可解析为整数的字符串。根据运行时,它不是。

您可以改用TryParse 使代码更具弹性。像这样的:

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】:

    简答,使用Binding

    为了构建示例,我将假设您没有指定 Winforms,但如果它是 WPF,请纠正我。反正基本原理是一样的。

    这个想法是将一个属性绑定到控件文本,它将直接从控件接收 解析 数字。绑定引擎将验证正确性,并在出现错误时提供视觉线索,并且该属性可以在任何进一步的代码中安全使用。

    一个示例实现可能是这样的:

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

    也就是说,代码直接使用属性而不是控件,而绑定负责两者之间的转换。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多