How to update label text in vb.net
In my vb.net winform application, on click of start button the label1.text should be "process started" then some filesaving method will run after finish that method the label1.text should change to "file saved".
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
lblStatus.ForeColor = Color.Red
lblStatus.Text = "Saving to File"
'Get the values and write to xls
Trigger()
SaveXls()
lblStatus.Text = "File Saved"
lblStatus.ForeColor = Color.Green
End Sub
the initial status of label "saving to file" is not comingup. after the Trigger method finished, the status of the label 开发者_运维技巧is changing to "File saved"
Any suggestions please?
You need to use the Refresh() method of the label. Using Application.DoEvents has side effects and should be used carefully (this is not the appropriate use for it).
Alternative to the other two answers (and my preference) would be to use Background Worker to execute Trigger()
and SaveXls()
.
Your code will look something like:
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
lblStatus.ForeColor = Color.Red
lblStatus.Text = "Saving to File"
If backgroundWorker1.IsBusy <> True Then
' Start the asynchronous operation.
backgroundWorker1.RunWorkerAsync()
End If
End Sub
Private Sub backgroundWorker1_DoWork(ByVal sender As System.Object, _
ByVal e As DoWorkEventArgs) Handles backgroundWorker1.DoWork
'Get the values and write to xls
Trigger()
SaveXls()
End Sub
Private Sub backgroundWorker1_RunWorkerCompleted(ByVal sender As System.Object, _
ByVal e As RunWorkerCompletedEventArgs) Handles backgroundWorker1.RunWorkerCompleted
If e.Cancelled = True Then
lblStatus.Text = "Canceled!"
lblStatus.ForeColor = Color.Black
ElseIf e.Error IsNot Nothing Then
lblStatus.Text = "Error: " & e.Error.Message
Else
lblStatus.Text = "File Saved"
lblStatus.ForeColor = Color.Green
End If
End Sub
Using Background Worker will also leave your form responsive while the background operation is happening instead of freezing it.
after set the label text initially, refresh the form using form1.refresh(). Then Trigger() and SaveXls() functions will execute and finally change the label text to "filesaved".
Thanks for all ur replies and efforts
You'll need to quit blocking your code for a moment after you update your lblStatus label. You can try putting an Application.DoEvents
after your first label update. Otherwise, your form will wait to refresh until your entire code block has finished executing. Application.DoEvents
will suspend your current thread, process the windows messages, and then continue executing once finished.
精彩评论