How can I filter data from dataset to datatable? like the code->
DataRow[] dr = DS.Tables[0]
.Select("STAGENAME='Develop' AND DEVLAPSEDAYS IS NOT NULL");
How can I use datatable here?
following code doesn`t reflect changes->
DataTable FilteredDataD = DS.Tables[0];
if (FilteredDataD.Rows.Count > 0) {
FilteredDataD.DefaultView.RowFilter = "STAGENAME='Develop' AND DEVLAPSEDAYS IS NOT NULL";
FilteredDataD.DefaultView.ToTable();
}
Is is possible to remove a column using above filter,like "STAGENAME='Develop' AND DEVLAPSEDAYS IS NOT NULL" + FilteredDataD.column("col_name")... Suppose I have 5 columns display only 4,I can`t remove col_name from my query.Is there a way?
Reply
Try using LINQ instead:
var table = DS.Tables[0].AsEnumerable().Where(
r => r.Field<string>("STAGENAME") == "Develop" && r.Field<int?>("DEVLAPSEDAYS").HasValue).AsDataView().ToTable();
EDIT Changed AsDataView
to AsDataView()
for syntactical accuracy.
EDIT Provided .NET 2.0 compatible solution
DataTable table = DS.Tables[0];
if (table.Rows.Count > 0)
{
table.DefaultView.RowFilter = "STAGENAME = 'DEVELOP' AND DEVLAPSEDAYS IS NOT NULL";
table = table.DefaultView.ToTable();
}
You could write an extension method (using C# 3) like follows:
public static DataTable Filter(this DataTable dataTable, string selectFilter)
{
var filteredTable = dataTable.Clone();
var rows = dataTable.Select(selectFilter).ToList();
rows.ForEach(filteredTable.ImportRow);
return filteredTable;
}
Then use it like follows:
DataTable dataTable = DS.Tables[0]
.Filter("STAGENAME='Develop' AND DEVLAPSEDAYS IS NOT NULL");
Update, since you said you are using C# 2.0 (and thus extension methods and LINQ aren't an option) you could use this instead:
public static DataTable GetFilteredTable(
DataTable sourceTable, string selectFilter)
{
var filteredTable = sourceTable.Clone();
var rows = sourceTable.Select(selectFilter);
foreach (DataRow row in rows)
{
filteredTable.ImportRow(row);
}
return filteredTable;
}
DataTable dataTable = GetFilteredTable(
DS.Tables[0], "STAGENAME='Develop' AND DEVLAPSEDAYS IS NOT NULL");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With