protected void Page_Load(object sender, EventArgs e)
{
string StartDate = Date3.Text;
string Enddate = Date4.Text;
ds = objBLL.GetUser(ItemType, ItemStatus);
dt = ds.Tables[0];
if (StartDate != null)
{
Filter records from datatable dt in such a way that
ParticipationStartDate > startDate");
}
if (Enddate != null)
{
Filter records from datatable dt in such a way that
ParticipationEndDate < EndDate
}
if(StartDate!=null && Enddate!= null)
{
i need to filter records from datatable such that
ParticipationStartDate > StartDate
and ParticipationEndDate < EndDate
}
}
GridView1.DataSource = dt; dt is the filtered datatable
GridView1.DataBind();
}
ParticipationStartDate,ParticipationEndDate 是数据表中的一列。 startdate 和 enddate 是 aspx 中的文本框字段。 所以这就是我想要做的。 如果 startdate(date3.text) 不为空,则数据表应给出记录,使得 ParticipationStartDate > startdate 如果 enddate(date4.text) 不为 null,则数据表应给出这样的记录 ParticipationEndDate < enddate
最佳答案
您可以使用 DataTable.DefaultView 功能进行过滤。示例:
if (StartDate != null)
{
dt.DefaultView.RowFilter="ParticipationStartDate > '"+startDate+"'";
}
然后:
GridView1.DataSource = dt.DefaultView; //note that you bind to DefaultView, not Datatable
GridView1.DataBind();
示例输出:
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("DirectoryName");
dt.Columns.Add("CreationTime");
for (int i = 0; i < 10; i++)
{
DataRow r = dt.NewRow();
r.ItemArray = new object[] { "Name "+i,"Directory "+i, new DateTime(2011,10,15,23,22,i,0)};
dt.Rows.Add(r);
} //populated DataTable with 10 rows. Creation Time artificially set
//set filter to creation time >= 2011/10/15 23h 22m 4sec
dt.DefaultView.RowFilter = "CreationTime >= '" + new DateTime(2011, 10, 15, 23, 22, 4, 5) + "'";
rpt.DataSource = dt.DefaultView;
rpt.DataBind();
在过滤后的数据表上只产生 6 条记录:
关于c# - 根据文本框值过滤数据表/数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7775711/