2014-10-19 78 views
1

我一直在尋找了一段時間,現在的這個答案:轉換一個DataGridView單元格數值爲一個DateTime

我已經得到了有日期的細胞一個DataGridView,我需要在這個值cell DateTimePicker的DateTime值可以去我的DateTimePicker

到目前爲止,我已經這樣做了,但它不工作,它給了我一個System.FormatException(顯然它不能識別字符串作爲DateTime,這聽起來右)

這是問題代碼:

int index = ReservationDataGridView.SelectedRows[0].Index; 
string date = ReservationDataGridView[0, 1].Value.ToString(); 
DateTime test = DateTime.ParseExact(date, "dd/MM/yyyy - hh:mm tt", System.Globalization.CultureInfo.InvariantCulture); 

MessageBox.Show(test.ToString() 

這是我的DateTimePicker如何格式化:

ReservationDateTimePicker.Format = DateTimePickerFormat.Custom; 
ReservationDateTimePicker.CustomFormat = "dd/MM/yyyy - hh:mm tt"; 

這是日期,如何看待在DataGridView:

DataGridView

如何我可以轉換DataGridView中的日期值的任何想法成DateTimePicker與該formaT適合的日期時間?

+0

我很抱歉,但我不明白你的意思 - 編輯:哦,那是因爲數據源是一個數據庫和用戶將從datagridview的選擇,雖然現在你這麼說我可以從數據庫中取出它。 – krieg 2014-10-19 23:31:18

+0

我提前說過,你說得對,我可以通過實體框架很容易地從數據庫中獲取日期。如果你想要代表,或官方承認只是將它作爲答案,我會檢查它。非常感謝! – krieg 2014-10-19 23:41:07

+0

沒問題..... – 2014-10-19 23:44:08

回答

0

而不是從DataGridview單元中獲取DateTime值的string表示,而是從DataDridview的數據源中檢索實際的DateTime值。

3

將datagridview單元格值轉換爲datetime的最佳方法是使用convert函數。 如果您正在通過dataGridView使用循環。例如說for Loop。

for(int i=0; i<dataGridView1.Rows.Count; i++) 
{ 
    DateTime date = Convert.ToDateTime(dataGridView1.Rows[i].Cells[1].Value.ToString()); 
} 

如果您沒有使用任何通過dataGridView的循環而不是簡單地使用下面的代碼。

DateTime date2 = Convert.ToDateTime(dataGridView1.CurrentRow.Cells[0].Value.ToString()); 

如果您使用dataGridView1 CellContent Click事件比使用下面的代碼。

private void grd_All_Degrees_CellClick(object sender, DataGridViewCellEventArgs e) 
{ 
    DateTime date3 = Convert.ToDateTime(grd_All_Degrees.Rows[e.RowIndex].Cells[0].Value.ToString());  
} 
相關問題