2012-09-10 92 views
-3
private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) 
    { 
     try 
     { 
      if ((dataGridView1.Focused) && (dataGridView1.CurrentCell.ColumnIndex == 0)) 
      { 
       dtpInstallment.Location = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false).Location; 
       dtpInstallment.Visible = true; 
       if (dataGridView1.CurrentCell.Value != DBNull.Value) 
       { 
        // dtpInstallment.Value = DateTime.Today; 
        dtpInstallment.Value = (DateTime)dataGridView1.CurrentCell.Value; 

       //  DateTime date = (DateTime)dataGridView1.CurrentCell.Value; 
       // dtpInstallment.Value = DateTime.Parse(date.ToString("dd/MM/yyyy")); 


       } 
       else 
       { 
        dtpInstallment.Value = DateTime.Today; 
       } 
      } 
      else 
      { 
       dtpInstallment.Visible = false; 
      } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
    } 

在這個日期被拋出異常......存在dataGridView1.CurrentCell.Value..but值無法轉換爲dtpInstallment.value這是DateTimePicker日期時間在C#中引發異常指定的轉換是無效

+0

裏面是什麼'dataGridView1.CurrentCell.Value'? – Habib

+0

它正在從datagridcell中取數據,它正在從數據庫中獲取數據的值... –

回答

2

這是因爲您正在解析的值不是正確的格式。嘗試使用ParseExact

string poop = "2005-12-14 23:12:34"; 
string currentFormat = "yyyy-MM-dd HH:mm:ss"; 
DateTime poo = DateTime.ParseExact(poop, currentFormat, System.Globalization.CultureInfo.InvariantCulture); 
// yyyy-MM-dd HH:mm:ss ==> you can change the format that matches the current 
//       value of your dataGridView1.CurrentCell.Value 
+1

您如何可能假設這一點? – MichaelT

+0

string dt = dataGridView1.CurrentCell.Value.ToString(); DateTime date = DateTime.ParseExact(dt,「yyyy-MM-dd」,System.Globalization.CultureInfo.InvariantCulture); dtpInstallment.Value = date; 現在我使用這個...它再次拋出異常... –

+0

@MichaelT從OP的短語'有dataGridView1.CurrentCell.Value中的值..但不能轉換爲DateTimePicker的dtpInstallment.value所以我認爲有一個無效格式的日期。 –

1

單元格中的值不是有效日期。也許試試DateTime.TryParse。這樣,如果它是一個有效的格式,你將得到一個DateTime,如果它不是一個有效的格式。

0

既然你檢查DBNull.Value,我猜你使用SqlDataSource檢索數據,而你的日期時間值的確是SqlDateTime

+0

是的,它是SqlDateTime類型.. –

1

嘗試使用CellContentClick事件

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) 
{ 
DateTime dtpInstallment = DateTime.Parse(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()); 
} 

然後用dataGridView1_CellBeginEdit事件