我正在嘗試編寫一個簡單的GUI應用程序,用於在單擊檢索按鈕時從Customer類加載客戶數據。然後,當點擊保存按鈕時,這些數據將存儲在Customer對象中。C#:從字符串轉換爲DateTime時出現未處理的異常
我通過測試發現,我清晰和檢索按鈕按預期工作,但我收到以下錯誤消息,當我按下保存按鈕:
未處理的異常發生在您的應用程序。如果您單擊繼續,應用程序將忽略此錯誤並嘗試繼續。如果您單擊退出,應用程序將立即關閉。
該字符串未被識別爲有效的DateTime。有一個未知的單詞從索引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的文本(也許這是關鍵:將地址字符串轉換爲datetime)?錯誤非常明顯:字符串未被識別爲有效的DateTime – prime23 2013-03-14 03:34:21
而且我建議您使用DateTimePicker控件讓用戶輸入日期而不是文本框 – prime23 2013-03-14 03:41:16
您使用的日期字段格式是什麼? – ecampver 2013-03-14 03:42:07