【问题标题】:C#: Unhandled Exceptions when Converting from String to DateTimeC#:从 String 转换为 DateTime 时出现未处理的异常
【发布时间】:2013-03-02 07:04:26
【问题描述】:

我正在尝试编写一个简单的 GUI 应用程序,该应用程序将在单击检索按钮时从 Customer 类加载客户数据。然后,当单击保存按钮时,此数据将存储在 Customer 对象中。

我通过测试发现我的清除和检索按钮按预期工作,但是当我按下保存按钮时收到以下错误消息:

您的应用程序中发生了未处理的异常。如果单击继续,应用程序将忽略此错误并尝试继续。如果单击退出,应用程序将立即关闭。

字符串未被识别为有效的日期时间。从索引 4 开始有一个未知单词。

我在下面粘贴了我的代码。我希望你们能提供任何澄清。提前谢谢!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace simple_GUI
{

    public partial class Form1 : Form
    {

        Customer myCustomer = new Customer(); //Declare an instance of the customer class within my Windows form

        public Form1()
        {
            InitializeComponent();
        }

        private void saveButton_Click(object sender, EventArgs e)
        {
            myCustomer.Id = Convert.ToInt32(customerIDTextBox.Text); //How to handle exceptions within my conversions?
            myCustomer.Name = fullNameTextBox.Text;
            myCustomer.Address = addressTextBox.Text;
            myCustomer.Email = emailTextBox.Text;
            myCustomer.Phone = Convert.ToDouble(phoneNumberTextBox.Text);
            myCustomer.AddDate = Convert.ToDateTime(addressTextBox.Text);
            myCustomer.TotalTransactions = Convert.ToInt32(totalTransactionsTextBox.Text);


        }

        private void retrieveButton_Click(object sender, EventArgs e)
        {
            customerIDTextBox.Text = Convert.ToString(myCustomer.Id); 
            fullNameTextBox.Text = myCustomer.Name;
            addressTextBox.Text = myCustomer.Address;
            emailTextBox.Text = myCustomer.Email;
            phoneNumberTextBox.Text = Convert.ToString(myCustomer.Phone);
            addDateTextBox.Text = Convert.ToString(myCustomer.AddDate);
            totalTransactionsTextBox.Text = Convert.ToString(myCustomer.TotalTransactions);

        }

        private void clearButton_Click(object sender, EventArgs e)
        {
            customerIDTextBox.Text = "";
            fullNameTextBox.Text = "";
            addressTextBox.Text = "";
            emailTextBox.Text = "";
            phoneNumberTextBox.Text = "";
            addDateTextBox.Text = "";
            totalTransactionsTextBox.Text = Convert.ToString(""); 

        }
    }
}

【问题讨论】:

  • addressTextBox 的文本是什么(也许这是关键:将地址字符串转换为日期时间)?错误很清楚:字符串未被识别为有效的日期时间
  • 我建议你使用 DateTimePicker 控件让用户输入日期而不是文本框
  • 您的日期字段使用什么格式?

标签: c# .net datetime exception-handling


【解决方案1】:

你可以尝试一个演员,如果它不起作用,你可以做点什么吗?

private bool ValidInteger(string value)
{
    int notUsed=0;
    return Int32.TryParse(value, out notUsed);
}

我删除了 function 关键字。代码现在可以编译了。

【讨论】:

    【解决方案2】:

    你可以在直接设置值转换之前检查是否可以转换,使用类型的TryParse()方法,你可以进行正确的转换,试试这样的方法

    private void saveButton_Click(object sender, EventArgs e)
    {
        // check if the Id is a integer
        int convertedId;
        if (!int.TryParse(customerIDTextBox.Text, out convertedId))
        {
            MessageBox.Show("The ID is not a integer value");
            return;
        }
    
        myCustomer.Id = convertedId;
        myCustomer.Name = fullNameTextBox.Text;
        myCustomer.Address = addressTextBox.Text;
        myCustomer.Email = emailTextBox.Text;
        myCustomer.Phone = phoneNumberTextBox.Text;
    
        // check if the DateTime is a valid dateTeime
        DateTime convertedDate;
        if (!DateTime.TryParseExact(addressTextBox.Text,"MM/dd/yyyy", null, System.Globalization.DateTimeStyles.AssumeLocal, out convertedDate))
        {
            MessageBox.Show("The filed is not a valid date");
            return;
        }
    
        myCustomer.AddDate = convertedDate;
    
    
        myCustomer.TotalTransactions = Convert.ToInt32(totalTransactionsTextBox.Text);
    }
    

    【讨论】:

      【解决方案3】:

      您可以通过添加一些代码来验证输入,以 AddDate 为例:

      try{
         myCustomer.AddDate = Convert.ToDateTime(addressTextBox.Text);
      }
      catch
      {
         MessageBox.Show("Add Date is not valid");
         return;
      }
      

      如果可能,请使用 DatePicker 控件输入日期。

      【讨论】:

        【解决方案4】:

        我建议您在文本框上使用正确的命名。您的代码显示,当您保存日期时,您使用的是 addressTextBox.Text:

        myCustomer.AddDate = Convert.ToDateTime(addressTextBox.Text);
        

        我觉得应该是这样的:

        myCustomer.AddDate = DateTime.Parse(dateTextBox.Text,"MM/dd/yyyy");
        

        当用户选择日期时,最好使用 DateTimePicker 控件而不是 TextBox。希望这会有所帮助!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-03-12
          • 2014-11-10
          • 2017-05-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多