我必须在我的VB.NET程序中使用进度条,其行为与VB6中的进度条非常不同.例如,如果我有一个程序通过某个循环填充datagridview并显示进度条的进度发生了什么? Datagridview填充率为100%,而进
Datagridview填充率为100%,而进度条达到约50%!
这是用于说明问题的示例程序.
创建一个新项目,添加一个Windows窗体,只需在Form1的代码上复制此代码.
Public Class Form1 Dim myMax As Integer = 100000 Dim pb As New ProgressBar Dim dgv As New DataGridView Dim WithEvents ti As New Timer Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load With Me .Width = 400 .Height = 250 .Controls.Add(pb) With pb .Maximum = myMax .Dock = DockStyle.Bottom End With .Controls.Add(dgv) With dgv .ColumnCount = 2 .Dock = DockStyle.Fill .Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill .Visible = False End With End With ti.Start() End Sub Private Sub OnFormLoaded(ByVal sender As Object, ByVal e As EventArgs) Handles ti.Tick ti.Enabled = False ti.Dispose() Dim temp As Integer For t = 0 To myMax If t Mod 100 = 0 Then pb.Value = t pb.Refresh() Application.DoEvents() temp += 1 dgv.Rows.Add(New String() { _ t.ToString, _ temp.ToString _ }) End If Next pb.Value = myMax pb.Visible = False dgv.Visible = True dgv.Focus() End Sub End Class
此代码创建几个控件,加载表单并启动循环以填充数据并显示进度条中的进度.在该程序隐藏了一个进度条并显示datagridview后,具体(真实世界)程序的常见情况如何.
问题在于,尽管datagridview填充和更新进度条都来自同一循环(步长为100),datagridview的填充结果比进度条显示进度快得多,并将其隐藏在约50%.
这与VB6有很大不同,其中填充和显示完全同步,并且在进度条达到100%的值后将显示网格.
如何在VB.NET中显示进度条的这种功能显示代码?
我尝试刷新progressbar和DoEvents但这还不足以让它按预期工作.
这种方法可以解决您的具体问题:
If t Mod 100 = 0 Then pb.Value = t If pb.Value > 0 Then pb.Value -= 1 temp += 1 dgv.Rows.Add(New String() { _ t.ToString, _ temp.ToString _ }) End If