We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you a podcast all about Citrix Workspace, moving to the cloud, and analytics & intelligence. Episode 2 coming soon!Listen Now

x

DataGridView - Display only last 5 rows of a database table.

Medium Priority
1,476 Views
Last Modified: 2013-11-27
Using Visual Studio 2005 Express and Microsoft Access.

I have a form with a DataGridView (read only) that I want to show only the last 5 rows of a database table. The user adds a row to the table via textboxes and a "Add" button (insert into). When records are added to the table, I want the DGV to refresh and still only show the last 5 records in the table. Any ideas?
Comment
Watch Question

Project manager
CERTIFIED EXPERT
Commented:
Why don't you load only the latest 5 records like this:
SELECT TOP 5 * FROM myTable ORDER BY id DESC

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Top Expert 2007
Commented:
Here's an example of how to add the last 5 rows:

        Dim table As New DataTable()
        table.Columns.Add("No")

        For i As Integer = 1 To 20
            table.Rows.Add(i)
        Next

        'Add columns to datagridview
        Me.DataGridView1.Columns.Clear()
        For Each col As DataColumn In table.Columns
            Me.DataGridView1.Columns.Add(col.ColumnName, col.ColumnName)
        Next

        'Add last 5 rows
        For i As Integer = table.Rows.Count - 1 To _
            table.Rows.Count - 5 _
            Step -1

            Me.DataGridView1.Rows.Insert(0, table.Rows(i).ItemArray())

        Next

Author

Commented:
Dhaest & VBRocks,

Sorry for my delayed response..
I haven't had the time to try either suggestions, but both look as though they would list the "top 5" in the datagridview in descending order. Is it possible to show the "top 5" in ascending order?

Author

Commented:
I found both suggestions to work and I'm sure I'll be using both in the future, hence the point split...

 Thank you both for the suggestions.
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.