Home > Software engineering >  get the value of date cell datagridview into the datetimepicker c#
get the value of date cell datagridview into the datetimepicker c#

Time:05-16

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 wich is the index 4

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

CodePudding user response:

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}");
    }
}

enter image description here

CodePudding user response:

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!

  • Related