c# - 根据文本框值过滤数据表/数据集

标签 c# asp.net

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 条记录:

enter image description here

关于c# - 根据文本框值过滤数据表/数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7775711/

相关文章:

c# - 编译器错误地指示使用未分配的局部变量错误

c# - 多个多对多关系 Entity Framework

c# - 套接字同步发送优于异步开始发送/结束发送吗?

c# - 如何使用 System.Net.Mail 将带有大附件的邮件发送到 Google Apps?

c# - ASP.Net C#-发送电子邮件时捕获错误

asp.net - “Failed to enable constraints”错误在我的ASP.Net项目中不断出现(看似随机)

c# - SOAP 扩展实现

c# - 使用 .net HttpClient 请求 github-api 说禁止

asp.net - Ajax 控件工具包 日历控件在 DetailsView EditItemTemplate 中不起作用

asp.net - 是否可以更改每个应用程序池的 w3wp.exe 的名称?