簡體   English   中英

將DataGridView單元格值轉換為DateTime

[英]Convert a DataGridView Cell Value into a DateTime

我一直在尋找這個答案一段時間:

我有一個datagridview,其中有一個帶有日期的單元格,我需要將該單元格中的值設置為可以與DateTimePicker一起使用的DateTime值。

到目前為止,我已經完成了此操作,但是它不起作用,它給了我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的Date值轉換為適合該格式的DateTimePicker的DateTime的任何想法?

將datagridview單元格值轉換為datetime的最佳方法是使用convert函數。 如果您正在使用遍歷dataGridView的循環。 舉例說, for循環。

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());     
}

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM