C# c中的DateTime引发指定的异常转换无效

C# c中的DateTime引发指定的异常转换无效,c#,sql-server-2008,C#,Sql Server 2008,在此datetime中,正在引发异常…dataGridView1.CurrentCell.value.中有值…但无法转换为作为DateTimePicker的DTPiInstallation.value 这是因为您正在解析的值的格式不正确。尝试使用ParseExact 单元格中的值不是有效日期。也许你可以试试。这样,如果DateTime是有效格式,您将获得一个DateTime,如果不是,则不会出现异常。由于您检查了DBNull.Value,我猜您是使用SqlDataSource检索数据的,并且您的

在此datetime中,正在引发异常…dataGridView1.CurrentCell.value.中有值…但无法转换为作为DateTimePicker的DTPiInstallation.value


这是因为您正在解析的值的格式不正确。尝试使用ParseExact


单元格中的值不是有效日期。也许你可以试试。这样,如果DateTime是有效格式,您将获得一个DateTime,如果不是,则不会出现异常。

由于您检查了DBNull.Value,我猜您是使用SqlDataSource检索数据的,并且您的DateTime值确实是类型。

尝试使用CellContentClick事件

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

然后使用dataGridView1_CellBeginEdit事件

dataGridView1.CurrentCell.Value内部是什么?它从datagridcell.获取值,它从数据库获取日期值…您怎么可能假设这一点?字符串dt=dataGridView1.CurrentCell.Value.ToString;DateTime date=DateTime.ParseExactdt,yyyy-MM-dd,System.Globalization.CultureInfo.InvariantCulture;DTP安装。值=日期;现在我正在使用这个…它再次抛出异常…@MichaelT从OP的短语dataGridView1.CurrentCell.value中有值..但无法转换为dtpInstallment.value,它是DateTimePicker,因此我假设有一个格式无效的日期。@user1658556,在发生错误之前,dataGridView1.CurrentCell.value的值是多少?由于此转换失败,它将作为字符串而不是日期时间
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
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
 DateTime dtpInstallment = DateTime.Parse(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
}