简体   繁体   中英

How to query C# DataTable?

I have created and returned datatable, this table has 10 columns. Now i want to filter from this table based on some dynamic search parameters. How to do this? any idea would be timely help.

// This function will create and return the source table.
var DisplayTable = CreateQueryTable(); 

Here I want to do dynamic search like If col1=MyName and Col2=MyCity

ResultGrid.DataSource = DisplayTable;
ResultGrid.DataBind();
Panel1.Controls.Add(ResultGrid);

You can do this in these way,

1.Creating DataView Like

var dv = dataTable.DefaultView;
dv.RowFilter =  "col1='MyName' and Col2='MyCity'"; // if MyName and MyCity are literal string.

or

dv.RowFilter = "col1='"+MyName+"' and Col2 ='"+ MyCity +"'";// if MyName and MyCity are string variable.

2.With DataTable Select Method, It will return array of DataRow

var rows = dataTable.Select("col1='MyName' and Col2='MyCity'"); //if string literal

or

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;

you create DataView of your datatable and use Filter // Create a DataView DataView dv = new DataView(yourDataTable); dv.RowFilter = "col1='MyName' and Col2='MyCity'"; //Bind your grid with DataView

You can also use select method on your table

  DataRow[] foundRows;
  foundRows = yourDataTable.Select("col1='MyName' and Col2='MyCity'");

You can also use Linq To DataTable

var results = from myRow in yourDataTable.AsEnumerable()
where myRow.Field<string>("col1") == Myname &&
      myRow.Field<string>("Col2") == MyCity
select myRow;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM