dhana
dhana

Reputation: 83

How to transfer date data from datagridview to datetimepicker in c# windows application

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.

enter image description here

when i click the row header in datagridview the data are transfer to the text boxes and also in datetime picker

enter image description here

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

enter image description here

Upvotes: 0

Views: 5731

Answers (2)

Nyerguds
Nyerguds

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

Alper Şaldırak
Alper Şaldırak

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

Related Questions