views:

491

answers:

2

I need to select 5 most recent rows from cached Dataview object, is there any way to do that?

I've tried but Indexer DataColumn is empty. :

public static DataView getLatestFourActive()
{
    DataTable productDataTable = getAll().ToTable();
    DataColumn ExpressionColumn = new DataColumn("Indexer",typeof(System.Int32));
    ExpressionColumn.Unique = true;
    ExpressionColumn.AutoIncrement = true;
    ExpressionColumn.AllowDBNull = false;
    ExpressionColumn.AutoIncrementSeed = 0;
    ExpressionColumn.AutoIncrementStep = 1;
    productDataTable.Columns.Add(ExpressionColumn);

    DataView productFilteredView = productDataTable.DefaultView;
    productFilteredView.RowFilter = "isActive=1 and Indexer<4";
    return productFilteredView;
}

getAll() returns cached DataView

thanks

A: 
getALL().Take(5);
Yongwei Xing
you'll probably want a .OrderByDescending() on there as well.
GordonB
I don't have Take() method, probably this comes with typed Datasets only using LINQ. I have untyped Dataview from simple SqlDataAdpater.Fill() method.
eugeneK
+1  A: 

I encountered the same sample above in this article, but the last post says the provided code doesn't work.

However, this article has a solution that does work, so here's the code you could use:

public static DataView getLatestFourActive() {
    DataTable productDataTable = getAll().ToTable();
    DataTable cloneDataTable = productDataTable.Clone();

    for (int i = 0; i < 4; i++) {
        cloneDataTable.ImportRow(productDataTable.Rows[i]);
    }       
    return new DataView(cloneDataTable);
}
Prutswonder
Did the job, thanks !
eugeneK