【问题标题】:filter a datatable/dataset based on textbox values根据文本框值过滤数据表/数据集
【发布时间】:2011-10-15 04:19:22
【问题描述】:
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) 不为 null,则数据表应提供 ParticipationStartDate > startdate 的记录 如果 enddate(date4.text) 不为 null,则数据表应给出 ParticipationEndDate 的记录

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    您可以使用 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 条记录:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-10
      • 2021-03-22
      • 2020-08-08
      • 2020-09-22
      • 1970-01-01
      相关资源
      最近更新 更多