简体   繁体   中英

How to get the value of date cell datagridview into the datetimepicker?

First thing go to datagridview event MouseClick, and write the code below:

DateTime dateValueOftheCell = DateTime.Parse(dataGridView1.CurrentRow.Cells[4].Value.ToString());
dateTimePicker1.Value = dateValueOftheCell.Date;

in my case my datagridview has the date value in the 5th column which is the index 4

index start from 0, index value = number of columns - 1 5 - 1 = 4

You should setup the DataGridView DataSource property to a BindingSource which allows easy access to the current row data. Also you can index into the BindingSource to get a specific row as shown below which is hard coded to get the third row data.

public partial class Form2 : Form
{
    private readonly BindingSource _bindingSource = new BindingSource();
    public Form2()
    {
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Id", typeof(int));
        dt.Columns.Add("BirthDate", typeof(DateTime));
        dt.Rows.Add(1, new DateTime(2020, 1, 1));
        dt.Rows.Add(2, new DateTime(1978, 9, 11));
        dt.Rows.Add(3, new DateTime(1987, 3, 2));

        _bindingSource.DataSource = dt;

        dataGridView1.DataSource = _bindingSource;
        dateTimePicker1.DataBindings.Add("Value", _bindingSource, "BirthDate");
    }

    private void GetButton_Click(object sender, EventArgs e)
    {
        var row = ((DataRowView)_bindingSource[2]).Row;
        MessageBox.Show($@"Birth is {row.Field<DateTime>("BirthDate"):d}");
    }
}

在此处输入图像描述

Using LINQ, I've created a simple code for Mouse Click event.

private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
    {
        int idx = dataGridView1.CurrentRow.Index;

        if (dataGridView1.Rows[idx].Cells[1].Value.ToString() != "") //Cells[1] = datetime column index
        {
            dateTimePicker1.Value = (DateTime)dataGridView1.Rows.Cast<DataGridViewRow>().ToList().Where(s => s.Index == idx && s.Cells[1].Value != null).Select(s => s.Cells[1].Value).FirstOrDefault();
        }
    }

I hope it helps!

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