views:

243

answers:

4

I want to return the top 5 records of a table in a dataset for datagrid view. The following does not work.

DataGridView.DataSource = DS.Tables("TABLENAME").Select("SELECT TOP 5")

Any suggestions?

Using Visual Studio 2008 - VB.Net

A: 

How about using the TOP clause. THis assume you are using SQL Server.

ie Select top 5 * from SomeTable

If you are using MySQL there is the limit clause

If you are using Oracle lookup ROWNUM

Gray Area
A: 

Select doesn't work like that, take a look at the syntax.

What you want to do is create a View with your table, sort it and take the first five rows.

DataView view = DS.Tables[0];
view.Sort = "myColumn";
//Take first or last 5 rows.

Or of course just use a "SELECT TOP 5 x from mytable" and insert that into your datatable.

Carra
A: 

If you're using SQL Server 2005 or greater, you could use the ROW_NUMBER() function to number the rows, then use:

DS.Tables("TABLENAME").Select("row_number <= 5")
Dave Swersky
+1  A: 

If the dataset is already populated, you can use LINQ to take the first 5 rows from a table. (The more efficient method would be to handle this at the database, however.)

Dim rows = DS.Tables("Foo").Rows.Cast(Of DataRow)().Take(5)
Anthony Pegram
Any good sources for LINQ? Like I said I am using an access database for the back-end data store so if LINQ is preferred method I should learn.
JPJedi
LINQ is *a* method, not always the preferred method, but it's great for simplification of code. I'm a C# coder for the most part, so I would point you to Jon Skeet's "C# in Depth" book. Absent that, MSDN is always reliable.
Anthony Pegram