Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1279
  • Last Modified:

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

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?
0
Tim313
Asked:
Tim313
  • 2
2 Solutions
 
DhaestCommented:
Why don't you load only the latest 5 records like this:
SELECT TOP 5 * FROM myTable ORDER BY id DESC
0
 
VBRocksCommented:
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

0
 
Tim313Author 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?
0
 
Tim313Author 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.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now