Reputation: 3683
I have a DataTable with information about users and I want to search for a user or a list of users in this DataTable.
Here is my C# code:
public DataTable GetEntriesBySearch(string username,string location,DataTable table)
{
list = null;
list = table;
string expression;
string sortOrder;
expression = "Nachname = 'test'";
sortOrder = "nachname DESC";
DataRow[] rows = list.Select(expression, sortOrder);
list = null; // for testing
list = new DataTable(); // for testing
foreach (DataRow row in rows)
{
list.ImportRow(row);
}
return list;
}
Upvotes: 95
Views: 437462
Reputation: 299
Sometimes you actually want to return a DataTable
than a DataView
. So a DataView
was not good in my case and I guess few others would want that too. Here is what I used to do
myDataTable.select("myquery").CopyToDataTable()
This will filter myDataTable
which is a DataTable and return a new DataTable
Upvotes: 14
Reputation: 699
use it:
.CopyToDataTable()
example:
string _sqlWhere = "Nachname = 'test'";
string _sqlOrder = "Nachname DESC";
DataTable _newDataTable = yurDataTable.Select(_sqlWhere, _sqlOrder).CopyToDataTable();
Upvotes: 24
Reputation: 69
Hi we can use ToLower Method sometimes it is not filter.
EmployeeId = Session["EmployeeID"].ToString();
var rows = dtCrewList.AsEnumerable().Where
(row => row.Field<string>("EmployeeId").ToLower()== EmployeeId.ToLower());
if (rows.Any())
{
tblFiltered = rows.CopyToDataTable<DataRow>();
}
Upvotes: 2
Reputation: 460058
If you're using at least .NET 3.5, i would suggest to use Linq-To-DataTable
instead since it's much more readable and powerful:
DataTable tblFiltered = table.AsEnumerable()
.Where(row => row.Field<String>("Nachname") == username
&& row.Field<String>("Ort") == location)
.OrderByDescending(row => row.Field<String>("Nachname"))
.CopyToDataTable();
Above code is just an example, actually you have many more methods available.
Remember to add using System.Linq;
and for the AsEnumerable
extension method a reference to the System.Data.DataSetExtensions
dll (How).
Upvotes: 144
Reputation: 443
For anybody who work in VB.NET (just in case)
Dim dv As DataView = yourDatatable.DefaultView
dv.RowFilter ="query" ' ex: "parentid = 0"
Upvotes: 11
Reputation: 3214
You can use DataView.
DataView dv = new DataView(yourDatatable);
dv.RowFilter = "query"; // query example = "id = 10"
http://www.csharp-examples.net/dataview-rowfilter/
Upvotes: 153
Reputation: 6055
It is better to use DataView for this task.
Example of the using it you can find in this post: How to filter data in dataview
Upvotes: 5