[英]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.