【问题标题】:Textbox value change on runtime exception [closed]运行时异常的文本框值更改[关闭]
【发布时间】:2017-11-20 16:13:17
【问题描述】:

我在运行时更改Textbox 的值,但是当用户使用退格键清除Textbox 时,我得到了无效字符串的异常。

private void txtTradePrice_TextChanged(object sender, EventArgs e)
{
    txtRate.Text = (Convert.ToInt32(txtTradePrice.Text) * 12).ToString();
}

private void txtRate_TextChanged(object sender, EventArgs e)
{
    txtTradePrice.Text = (Convert.ToInt32(txtRate.Text) / 12).ToString();
}

【问题讨论】:

  • 因为空字符串不能转换为整数。看看使用 Int.TryParse() 代替。
  • Google 获取通用错误文本。
  • 您得到的字符串无效,因为您无法将空字符串转换为 int。此外,据我所知,在属性上设置.Text 字段将触发TextChanged 事件,因此您将获得循环触发。

标签: c# winforms textbox


【解决方案1】:

您的代码必须检查字符串是否为空。当用户清除文本时,文本变为空,Convert to int 将抛出异常,它不能将空白转换为整数值。

private void txtTradePrice_TextChanged(object sender, EventArgs e)
{
   if(!string.IsNullOrEmpty(txtTradePrice.Text))
   {        
     int number;
     if(Int32.TryParse(txtTradePrice.Text, out number))          
       txtRate.Text = (number * 12).ToString();
   }
}

private void txtRate_TextChanged(object sender, EventArgs e)
{
   if(!string.IsNullOrEmpty(txtRate.Text))    
   {
      int number;          
      if(Int32.TryParse(txtRate.Text, out number))          
         txtTradePrice.Text = (number / 12).ToString();
   }
}

您应该始终使用 Int.TryParse。

【讨论】:

    【解决方案2】:

    您应该使用 int.TryParse,因为它可以处理字符串问题。

    private void txtTradePrice_TextChanged(object sender, EventArgs e)
    {
        int tradePrice = 0;
        if(int.TryParse(txtTradePrice.Text, out tradePrice))
            txtRate.Text = (tradePrice * 12).ToString();
    }
    
    private void txtRate_TextChanged(object sender, EventArgs e)
    {
        int rate = 0;
        if(int.TryParse(txtRate.Text, out rate))
            txtTradePrice.Text = (rate / 12).ToString();
    }
    

    有了这个,当字段为空时,不会重新计算任何内容,或者会出现任何其他文本问题(如输入中的无效字符)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-23
      • 1970-01-01
      • 2013-01-16
      • 2012-07-12
      • 2023-02-10
      • 2015-03-03
      相关资源
      最近更新 更多