How to filter a dataview from the ith row to jth row? (C#)
I know there's the RowFilter
option to filter according to column value. Also there are methods to choose the top N rows. But how do I filter out and get rows from (I prefer getting it to the same DataView
dv), say, position 10 to position 23?
Here's my requirement. I have a DataView
dv which has 100 rows. I have a listbox with 10 items. When I choose first item in the listbox, I want first 10 rows of the dataview to be loaded (loading part is in my program, leave it to me), if I choose 2nd item in listbox then I want row11 to row20 to be loaded and so on. I can do the listbox part, but how to choose datavie开发者_JAVA技巧w values based on row number?
This is how my code looks:
DataSet ds = new DataSet();
DataTable dt = ds.Tables["words"];
DataView dv = new DataView(dt);
Now how to have a dataview from dv based on row position?
Thanks.
You can utilize the extension methods provided in Linq to get rows by position. For example:
// just setting up a table for the sample
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
for (int i = 1; i <= 100; i++)
{
table.Rows.Add(i);
}
// grabbing rows 11 through 20 using Linq
DataTable filtered = table.AsEnumerable().Skip(10).Take(10).CopyToDataTable();
The above works with .NET 3.5+, C# 3.0+. For something that works in older versions of C# and .NET, you can do it manually in just a little more code.
// starting by cloning 'table' (see code above)
DataTable filtered = table.Clone();
int skipRows = 10;
int selectRows = 10;
for (int index = skipRows;
index < skipRows + selectRows && index < table.Rows.Count;
index++)
{
filtered.Rows.Add(table.Rows[index].ItemArray);
}
精彩评论