Introduction
I needed a way to hide an ASP.NET Label
control after a few seconds. I have a page where the user can write some text in a textbox, click Submit, then a label displays "Saved!" -- I wanted that label to disappear after a few seconds in case the user wanted to edit the text and save again, thus displaying the saved label for a few more seconds.
Nothing too complicated, just some VB code that iterates through all the controls on the page, looks for a Label
control with the first few chars of the ID matching "lblStatus" or "lblSaved", then writes the JavaScript block to hide those controls after a few seconds.
I have applied this code within a class I call "commonFunctions
" and I call it from my master page Load
event:
commonFunctions.hideAllStatusLabelsAfterXSecs(Page)
Hopefully the code is self-explanatory and you can modify it for your needs. It can apply to any type of control, not just Label
s.
Public Shared Function hideAllStatusLabelsAfterXSecs(ByVal mePage As Page)
Dim xsecs As Integer = 2
Dim realSecs As Integer = xsecs * 1000
Dim theScript As New StringBuilder
theScript.Append("<script type='text/javascript'>" + vbCrLf)
theScript.Append("// hide all status labels after X seconds" + vbCrLf)
Dim oControl As Control
Dim childc As Control
Dim labelall As Label
Dim countControls As Integer = 0
Dim jsCtrlStr As String
For Each oControl In mePage.Form.Controls
For Each childc In oControl.Controls
If TypeOf childc Is Label Then
labelall = CType(childc, Label)
If Left(childc.ID.ToString, 9) = "lblStatus" Or _
Left(childc.ID.ToString, 8) = "lblSaved" Then
countControls = countControls + 1
jsCtrlStr = "document.getElementById('" & _
childc.ClientID & "')"
theScript.Append("if (" & jsCtrlStr & " != null) ")
theScript.Append("var x" & countControls.ToString & _
" = setTimeout(""" & jsCtrlStr & _
".style.display='none'"", " & _
realSecs.ToString & ");" + vbCrLf)
End If
End If
Next
Next
theScript.Append("</script>")
mePage.ClientScript.RegisterStartupScript(GetType(String), _
"HideLabelControls", theScript.ToString)
Return "0"
End Function