簡體   English   中英

如何將日期單元格 datagridview 的值放入 datetimepicker?

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

首先去datagridview事件MouseClick,然后寫下面的代碼:

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

在我的情況下,我的 datagridview 在第 5 列中具有日期值,即索引 4

索引從 0 開始,索引值 = 列數 - 1 5 - 1 = 4

您應該將 DataGridView DataSource 屬性設置為允許輕松訪問當前行數據的 BindingSource。 您還可以索引 BindingSource 以獲取如下所示的特定行,該行經過硬編碼以獲取第三行數據。

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

在此處輸入圖像描述

使用 LINQ,我為鼠標單擊事件創建了一個簡單的代碼。

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

我希望它有幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM