Reputation: 83
I'm working on datagridview in c# windows forms application and I'm loading the data from the database,Now i want to edit the cell value and save the value to the database, Here i have date and time in my database.
when i click the row header in datagridview the data are transfer to the text boxes and also in datetime picker
data are copy in textbox correctly but it gives error message when copy in datetimepicker.
code i done.
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());
}
Error message is
Upvotes: 0
Views: 5731
Reputation: 5629
If you know the exact format in which the date and time will be in the grid, parse them accordingly:
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);
From the screenshot, your two DateTimePicker
controls do seem to both give a full date, though. You might want to change those so one only picks time and the other only picks a date.
Do make sure that to put your dates and times into the grid, you convert the DateTime objects to string using exactly the same format:
(where i
is the index you're currently editing)
dataGridView1.Rows[i].Cells[5].Value = dtpdate.Value.ToString("dd-MM-yyyy");
dataGridView1.Rows[i].Cells[6].Value = dtptime.Value.ToString("HH:mm:ss");
Upvotes: 2
Reputation: 1054
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"));
Upvotes: 0