【问题标题】:How to avoid "input string is not in correct format" error when passing a null value传递空值时如何避免“输入字符串格式不正确”错误
【发布时间】:2013-12-28 03:11:34
【问题描述】:

我有一个类,我也从我的文本框中传递一个值。我用int?在我也传递的类中,允许空值。每次我执行它都会给出输入字符串格式不正确的错误。我怎样才能让它允许空值?我考虑过创建一个只传递 string = "null" 的 if 语句。我把我的代码放在下面提前谢谢你。

这是我用来将值传递给我的类的方法,当我将其留空时会出现错误。

newGrid.EmployeeID = Convert.ToInt32(employeeIDTextBox.Text);
newGrid.JobID = Convert.ToInt32(JobIDTextBox.Text);

信息传递给我的类中的变量声明。

public int? JobID { get; set; }

【问题讨论】:

    标签: c# textbox


    【解决方案1】:

    改用TryParse

    Int32 employeeId;
    newGrid.EmployeeID = Int32.TryParse( employeeIDTextBox.Text, out employeeId ) ? employeeId : null;
    

    这确实需要多行语句。您可以将 TryParse 包装起来以简化这一点,如下所示:

    public static Int32? Int32TryParseSafe(String text) {
        Int32 value;
        return Int32.TryParse( text, out value ) ? value : null;
    }
    
    // Usage:
    newGrid.EmployeeID = Int32TryParseSafe( employeeIDTextBox.Text );
    

    【讨论】:

    • 好的,是使用第二种方法还是两者都用?
    • 错误1 无法确定条件表达式的类型,因为'int'和''之间没有隐式转换
    • 我需要它(int?)例如:? (int?)值
    【解决方案2】:
          int number;
          bool result = Int32.TryParse(employeeIDTextBox.Text, out number);
          if (result)
          {
             newGrid.EmployeeID=number;       
          }
          else
          {
          //whatever you want to do for bad values
          newGrid.EmployeeID=0;
          }
    

    【讨论】:

      【解决方案3】:

      您无法说服Convert.ToInt32 改变其行为,但您可以轻松获得自己想要的效果:

      string employeeID = employeeIDTextBox.Text;
      newGrid.EmployeeID = string.IsNullOrEmpty(employeeID) ? null : Convert.ToInt32(employeeID);
      

      请注意,虽然这比其他一些选项更简洁,但您并不像使用 TryParse 那样安全。如果用户输入非数字字符,这将失败。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多