需要添加一个student类
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
namespace Demo7
{
public partial class Form3 : Form
{
List<Student> students = null;
public Form3()
{
InitializeComponent();
BindDataGradView(); //绑定list数据
//开始时默认将俩个dateTimePicker内容置空
this.dtpStart.Format = DateTimePickerFormat.Custom;
this.dtpStart.CustomFormat = " ";
this.dtpEnd.Format = DateTimePickerFormat.Custom;
this.dtpEnd.CustomFormat = " ";
}
private void BindDataGradView() {
students = new List<Student>()
{
new Student() { Id = 1, Name = "张三", Age = 18, Sex = "男", bridaty = new DateTime(2024, 2, 15) },
new Student() { Id = 2, Name = "张三", Age = 18, Sex = "男", bridaty = new DateTime(2024, 3, 15) },
new Student() { Id = 3, Name = "张三", Age = 18, Sex = "男", bridaty = new DateTime(2024, 4, 15) },
new Student() { Id = 4, Name = "张三", Age = 18, Sex = "男", bridaty = new DateTime(2024, 5, 15) }
};
//在dataGridView1中显示数据并更改列名
dataGridView1.DataSource = students;
dataGridView1.Columns[0].HeaderText = "学生ID";
dataGridView1.Columns[1].HeaderText = "学生姓名";
dataGridView1.Columns[2].HeaderText = "学生年龄";
dataGridView1.Columns[3].HeaderText = "学生性别";
dataGridView1.Columns[4].HeaderText = "学生生日";
}
//改变两个dateTimePicker的value时通过改变格式将日期显示
private void dtpStart_ValueChanged(object sender, EventArgs e)
{
this.dtpStart.Format = DateTimePickerFormat.Long;
this.dtpStart.CustomFormat = null;
}
private void dtpEnd_ValueChanged(object sender, EventArgs e)
{
this.dtpEnd.Format = DateTimePickerFormat.Long;
this.dtpEnd.CustomFormat = null;
}
//得到该时间区间内符合的数据
private void btnSearch_Click(object sender, EventArgs e)
{
string sarttime = dtpStart.Text + "00:00:00";
string endtime = dtpEnd.Text + "23:59:59";
DateTime Sart = DateTime.Parse(sarttime);
DateTime End = DateTime.Parse(endtime);
List<Student> filesStudent = students;
if (!string.IsNullOrWhiteSpace(dtpStart.Text))
{
filesStudent = filesStudent.Where(s => s.bridaty >= Sart).ToList();
}
if (!string.IsNullOrWhiteSpace(dtpEnd.Text))
{
filesStudent = filesStudent.Where(s => s.bridaty <= End).ToList();
}
dataGridView1.DataSource = filesStudent;
}
//清空将两个dateTimePicker清空方便重新搜索 清空时需将日期恢复成当前日期
private void btnClear_Click(object sender, EventArgs e)
{
dtpStart.Value = DateTime.Now;
dtpStart.Format = DateTimePickerFormat.Custom;
dtpStart.CustomFormat = " ";
dtpEnd.Value = DateTime.Now;
dtpEnd.Format = DateTimePickerFormat.Custom;
dtpEnd.CustomFormat = " ";
}
}
}