首页 文章

如何在c#windows应用程序中将日期数据从datagridview传递到datetimepicker

提问于
浏览
0

我正在c#windows窗体应用程序中处理datagridview,我正在从数据库加载数据,现在我想编辑单元格值并将值保存到数据库,这里我在数据库中有日期和时间 .

enter image description here

当我单击datagridview中的行 Headers 时,数据将传输到文本框以及日期时间选择器

enter image description here

数据在文本框中正确复制,但在datetimepicker中复制时会出现错误消息 .

我做的代码 .

private void dgvpbx_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            txtname.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
            cmbidentifier.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
            txtplace.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
            txtcity.Text = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
            dtpdate.Value = Convert.ToDateTime(dataGridView1.Rows[e.RowIndex].Cells[5].Value.ToString());
            dtptime.Value = Convert.ToDateTime(dataGridView1.Rows[e.RowIndex].Cells[6].Value.ToString());
        }

错误信息是

enter image description here

2 回答

  • 0

    如果您知道日期和时间在网格中的确切格式,请相应地解析它们:

    dtpdate.Value = DateTime.ParseExact(dataGridView1.Rows[e.RowIndex].Cells[5].Value.ToString(),
        "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture);
    dtptime.Value = DateTime.ParseExact(dataGridView1.Rows[e.RowIndex].Cells[6].Value.ToString(),
        "HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
    

    从截图中,您的两个 DateTimePicker 控件似乎都提供了完整的日期 . 您可能想要更改这些,因此只选择时间而另一个只选择日期 .

    确保将日期和时间放入网格中,使用完全相同的格式将DateTime对象转换为字符串:

    (其中 i 是您当前正在编辑的索引)

    dataGridView1.Rows[i].Cells[5].Value = dtpdate.Value.ToString("dd-MM-yyyy");
    dataGridView1.Rows[i].Cells[6].Value = dtptime.Value.ToString("HH:mm:ss");
    
  • 1
    dtpdate.Value = Convert.ToDateTime(dataGridView1.Rows[e.RowIndex].Cells[5].Value.ToString("dd-MM-yyyy"));
    dtptime.Value = Convert.ToDateTime(dataGridView1.Rows[e.RowIndex].Cells[6].Value.ToString("dd-MM-yyyy"));
    

相关问题