You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将数据库取出的日期值正确赋值显示到DateTimePicker控件中

问题原因

DateTimePicker控件的选中值不通过Text属性控制,你需要将从DataGridView中读取到的日期转换为DateTime类型后,赋值给控件的Value属性即可实现回显。

实现代码

private void dgvData_DoubleClick(object sender, EventArgs e)
{
    if(dgvData.CurrentRow.Index != -1)
    {
        Id = Convert.ToInt32(dgvData.CurrentRow.Cells[0].Value.ToString());
        txtName.Text = dgvData.CurrentRow.Cells[1].Value.ToString();
        txtAddress.Text = dgvData.CurrentRow.Cells[2].Value.ToString();
        
        // 日期回显逻辑,增加空值判断避免异常
        object dateCellValue = dgvData.CurrentRow.Cells[3].Value;
        if (dateCellValue != DBNull.Value && dateCellValue != null)
        {
            // 数据库字段为date类型时直接转换即可
            dateTimePicker1.Value = Convert.ToDateTime(dateCellValue);
        }
        else
        {
            // 日期为空时可设置默认值,也可根据业务需求调整逻辑
            dateTimePicker1.Value = DateTime.Today;
        }
    }
}

特殊情况兼容

如果你数据库中的日期实际存储为字符串格式(示例格式为M/d/yyyy),可以使用指定格式解析避免转换异常:

dateTimePicker1.Value = DateTime.ParseExact(dateCellValue.ToString(), "M/d/yyyy", System.Globalization.CultureInfo.InvariantCulture);

内容的提问来源于stack exchange,提问作者Sdtv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 17:36:00