简体   繁体   中英

C# Windows Form Passing DataGridView Cell Value of type Date to DateTimePicker

I'm pretty new to C#, I'm trying to implement a CellClick event on the DataGridView, so when clicked it passes the values from the grid to textboxes and a dateTimePicker.

I have built another dateTimePicker to store new data to SQL Database in a table called income. When storing it flips the formatting from dateTimePicker1 (dd-MM-YYYY) to (MM-dd-YYYY), so the table stores in a different order.

This is how I push it to the database at first:

using (connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=\\VBOXSVR\Projects\cw2\cw2\Database1.mdf;Integrated Security=True"))
using (SqlCommand cmd = new SqlCommand("INSERT INTO income(name,value,date) VALUES ('" + textBox1.Text + "','" + textBox2.Text + "','" + dateTimePicker1.Value.Date + "')", connection))
{
    connection.Open();
    cmd.ExecuteNonQuery();

    label1.Visible = true;
    label1.Text = "Db Upload Success!";
 }

So when triggering the return, the date appears in a table order, so the new dateTimePicker2 displays as on the table, so the original DateTimePicker1 date eg: 4th December 2018 is stored as 12/04/2018 on the table appears as 12th March 2018 on DateTimePicker2

Here's my attempt of passing the Datagrid values back to different textboxes and new dateTimePicker2:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
   int indexRow = e.RowIndex; // get the selected Row Index
   DataGridViewRow row = dataGridView1.Rows[indexRow];
   textBox3.Text = row.Cells[1].Value.ToString();
   textBox4.Text = row.Cells[2].Value.ToString();
   dateTimePicker2.Value = Convert.ToDateTime(row.Cells[3].Value);             
 }

I've done some research, but I can't just change the format in the local SQL Database which is set to date, but how could I format the date back to dd-MM-YYYY format?

尝试这个:

dateTimePicker2.Value = DateTime.ParseExact(row.Cells[3].Value, "dd-MM-yyyy", CultureInfo.InvariantCulture)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM