我创建并返回了数据表,这个表有10列。现在我想根据一些动态搜索参数从这个表中过滤。这该怎么做?任何想法都会得到及时的帮助。
// This function will create and return the source table.
var DisplayTable = CreateQueryTable();
在这里,我想进行动态搜索,例如If col1=MyName and Col2=MyCity
ResultGrid.DataSource = DisplayTable;
ResultGrid.DataBind();
Panel1.Controls.Add(ResultGrid);
答案 0 :(得分:6)
你可以这样做,
1.创建DataView Like
var dv = dataTable.DefaultView;
dv.RowFilter = "col1='MyName' and Col2='MyCity'"; // if MyName and MyCity are literal string.
或
dv.RowFilter = "col1='"+MyName+"' and Col2 ='"+ MyCity +"'";// if MyName and MyCity are string variable.
2.使用DataTable Select Method,它将返回DataRow数组
var rows = dataTable.Select("col1='MyName' and Col2='MyCity'"); //if string literal
或
var rows = dataTable.Select("col1='"+MyName+"' and Col2='"+MyCity+"'"); // if string variable
3.By Linq
var filterdData = from row in dataTable.AsEnumerable()
where row.Field<string>("col1") == "MyName"
&& row.Field<string>("col2") == "MyCity"
select row;
答案 1 :(得分:2)
您创建数据表的DataView并使用Filter //创建一个DataView DataView dv = new DataView(yourDataTable); dv.RowFilter =“col1 ='MyName'和Col2 ='MyCity'”; //使用DataView绑定网格
您还可以在桌面上使用select方法
DataRow[] foundRows;
foundRows = yourDataTable.Select("col1='MyName' and Col2='MyCity'");
您也可以使用Linq To DataTable
var results = from myRow in yourDataTable.AsEnumerable()
where myRow.Field<string>("col1") == Myname &&
myRow.Field<string>("Col2") == MyCity
select myRow;