本文介绍了如何以简单的方式过滤Dgv中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有更简单的方法以这种方式过滤DataGridView中的行?
Is there an easier way to filter rows in the DataGridView of this way ?
private void Reread()
{
string nameFilter = txtSearch.Text;
string addressFilter = comboBox1.SelectedIndex > 0 ? comboBox1.Text : "";
string depFilter = comboBox2.SelectedIndex > 0 ? comboBox2.Text : "";
DateTime? birthdate = chkBirthdate.Checked ? dateTimePicker1.Value.Date : (DateTime?) null;
DateTime? fromDate = chkRange.Checked ? dateTimePicker2.Value.Date : (DateTime?)null;
DateTime? toDate = chkRange.Checked ? dateTimePicker3.Value.Date : (DateTime?)null;
using (DbDataContext db = new DbDataContext())
{
var result = from p in db.Persons
where
(nameFilter.Length > 0 && p.FullName.Contains(nameFilter) || nameFilter.Length == 0)
&& (addressFilter.Length > 0 && p.Address == addressFilter || addressFilter.Length == 0)
&& (depFilter.Length > 0 && p.Department == depFilter || depFilter.Length == 0)
&& (birthdate == null || (birthdate != null && p.Birthdate == birthdate))
&& ((fromDate == null || toDate == null) || (fromDate != null && toDate != null && p.Birthdate >= fromDate && p.Birthdate <= toDate))
select p;
var resultData = result.ToList();
dataGridView1.DataSource = resultData;
}
推荐答案
//Build the query in stages taking advantage of deferred execution.
//select all Persons
var query = from p in db.Persons select p;
//apply nameFilter if valid
if (!string.IsNullOrEmpty(nameFilter))
{
query = query.Where(
n => n.fullName.Contains(nameFilter));
}
//apply addressFilter, if valid
if (!string.IsNullOrEmpty(addressFilter))
{
query = query.Where(a => a.Address == addressFilter);
}
//apply departmentFilter, if valid
if (!string.IsNullOrEmpty(depFilter))
{
query = query.Where(d => d.Department == depFilter);
}
//apply birthdateFilter, if valid
if (birthdate != null)
{
query = query.Where(b => b.Birthdate == birthdate);
}
//apply dateRangeFilter, if valid
if (birthdate != null && toDate != null && fromDate != null)
{
query = query.Where(dr.Birthdate >= fromDate && dr.Birthdate <= toDate);
}
//run the query
var results = query.ToList();
这篇关于如何以简单的方式过滤Dgv中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!