我创建了一个VB表单,它将SQL数据显示在列表视图中,列表视图每隔几秒刷新一次,以便在将新数据输入SQL表时显示新值。一切正常,但令人讨厌的问题是每次刷新时列表视图都会闪烁。有没有办法防止它闪烁?
我目前的代码如下。谢谢
Imports System.Data.SqlClient
Imports System.Drawing
Public Class Form1
Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim da As SqlDataAdapter
Dim ds As DataSet
Dim itemcoll(100) As String
Private WithEvents tmr As New Timer With {.Interval = 500}
Private R As New Random
Private Declare Function LockWindowUpdate Lib "user32" (ByVal hwndLock As Long) As Long
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
tmr.Start()
Call GetData()
End Sub
Private Sub GetData()
listview1.beginupdate
ListView1.HeaderStyle = ColumnHeaderStyle.None
Me.ListView1.View = View.Details
Me.ListView1.GridLines = False
Me.ListView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
Me.ListView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize)
Dim conn As New SqlConnection("Data Source=xxx;Initial Catalog=orders; User ID=xxx;Password=xxx")
Dim strQ As String = String.Empty
strQ = "SELECT productcode, productname, qty from dbo.ordertemptable"
cmd = New SqlCommand(strQ, conn)
da = New SqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "dbo.ordertemptable")
Dim i As Integer = 0
Dim j As Integer = 0
' adding the columns in ListView
For i = 0 To ds.Tables(0).Columns.Count - 1
Me.ListView1.Columns.Add(ds.Tables(0).Columns(i).ColumnName.ToString())
Next
'Now adding the Items in Listview
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
itemcoll(j) = ds.Tables(0).Rows(i)(j).ToString()
Next
Dim lvi As New ListViewItem(itemcoll)
Me.ListView1.Items.Add(lvi)
Me.ListView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
Next
listview1.endupdate
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
ListView1.Items.Clear()
ListView1.Columns.Clear()
Call GetData()
Timer1.Interval = 1000
Timer1.Enabled = True
ListView1.Refresh()
End Sub
End Class
答案 0 :(得分:1)
在更新之前使用BeginUpdate ListView方法,然后在添加新数据后使用EndUpdate ListView方法。这样可以防止在添加每个项目时不断刷新。