对DataTable的过滤

在实际的开发过程中,经常需要对查询出来的DataTable进行过滤,比如:页面初始化的时候显示出所有的记录,页面中
有查询框,当页面初始化之后利用查询框进行精确查找,这种情况我们通常采用的方法如下:
方法一、初始化的时候调用一个存储过程,当点击查询按钮的时候在调用另外一个存储过程,当然,这种逻辑是可以实现
        的,但是不提倡。
方法二、对页面初始化时候查询出的DataTable进行过滤,这正方法可行性比较高,具体如下:
 第一步:拼接筛选的具体字符串
  string filterExpression="";
  if (!string.IsNullOrEmpty(txtHouseBusinessNumber.Text))
                {
                    filterExpression = "物业编号='" + txtHouseBusinessNumber.Text + "' and ";
                }
                //合同编号
                if (!string.IsNullOrEmpty(txtContractContractNumber.Text))
                {
                    filterExpression += "合同编号='" + txtContractContractNumber.Text + "' and ";
                }
                //物业地址
                if (!string.IsNullOrEmpty(txtPropertyPAddress.Text))
                {
                    filterExpression += "物业地址 like '" + txtPropertyPAddress.Text + "'%";
                }
                if (filterExpression.EndsWith(" and "))
                {
                    int indexOfAnd=filterExpression.LastIndexOf(" and ");
                    filterExpression = filterExpression.Substring(0, indexOfAnd);
                }
 第二步:
                DataRow[] row=table.Select(filterExpression);
                DataTable newTable = table.Clone();
                for (int i = 0; i < row.Length; i++)
                {
                    newTable.ImportRow(row[i]);
                }

                DataView dtv = newTable.DefaultView;
                gvwData.DataSource = dtv;
                gvwData.DataBind();

原文地址:https://www.cnblogs.com/jsping/p/2637688.html