Click here to Skip to main content
15,885,914 members
Articles / Web Development / ASP.NET
Tip/Trick

ASP.NET Hide Controls after Number of Seconds

Rate me:
Please Sign up or sign in to vote.
4.56/5 (9 votes)
22 Jun 2010CPOL2 min read 35.5K   11   1
Hide Label/DIV Controls after number of seconds
I was looking for functionality to hide controls other than the Label control, hide multiple controls simultaneously and writing client-side JavaScript for re-use, so have put together an example code showing the implementation of the same.

Introduction

One of the functional requirements for my web page is to hide an ASP.NET Label Control after displaying it for number of seconds in response to button click event. I found few examples on Google.com but somewhat did not meet my constraint. I'm also looking for functionality to hide controls other than the Label control, hide multiple controls simultaneously and writing client-side JavaScript for re-use. I have put together an example code showing the implementation of the mentioned requirements.

Figure 1

results

Putting Everything Together

Shown below is the JavaScript function that accepts two parameters, namely ctrl and timer. The first parameter is a string that contains the control ID for HTML markup. We can pass in a single control ID or as many control IDs as we need from the code behind. See below for an example.

  1. ControlOne.ClientID
  2. ControlOne.ClientID + ","+ControlTwo.ClientID +", " + ControlThree.ClientID + …

The second parameter indicates how many milliseconds from now the application should hide the control. This JavaScript function will split the ctrl on the comma (,) and load the results into an array. Then it will loop through the array and set the element property display value to "none".

Listing 1

JavaScript
function HideCtrl(ctrl, timer) {
    var ctry_array = ctrl.split(",");
    var num = 0, arr_length = ctry_array.length;
    while (num < arr_length) {
        if (document.getElementById(ctry_array[num])) {
            setTimeout('document.getElementById
            ("' + ctry_array[num] + '").style.display = "none";', timer);
        }s
        num += 1;
    }
    return false;
}

Shown in listing 2 is the content of the .aspx file.

Listing 2

HTML
<div style="width: 90%;">
    <div style="background:#CCCFFF;padding:5px 0 6px 10px">Guess the number game</div>
    <div style="border:solid 1px #919191;padding:0 0 20px;min-height:100px;">
        <asp:Label ID="Label1" runat="server" Text="Enter a number between 1 and 5" />
         <asp:TextBox ID="txtAns" runat="server" Width="30px" />
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" 
                runat="server" ErrorMessage="*" 
                Display="Dynamic" ControlToValidate="txtAns" />
        <asp:RangeValidator ID="RangeValidator1" runat="server" 
                ErrorMessage="(1-5)" ControlToValidate="txtAns" 
                Display="Dynamic" MaximumValue="5" Type="Integer" 
                MinimumValue="1" />
                
            <asp:Button ID="btnExampleOne" runat="server" Text="Submit" />  
            
            <br /> <br /><asp:Label ID="lblMsg" runat="server" Text="" />
                        
            <div runat="server" visible="false" id="divBallon">
                <asp:Label ID="lblMsg2" runat="server" Text=""></asp:Label>
                <img src="images/ballons-07.gif" alt="ballons" />
            </div>
    </div>
</div>

Add the code shown in listing 3 to the page load events to direct the client not to store the responses in its history.

This will prevent the control from re-appearing when the user clicks on the browser back button.

Listing 3

HTML
Response.Cache.SetNoStore();

Displayed below is the code in the button click event. The code is pretty straight forward.
Use the ScriptManager.RegisterStartupScript() method if the ASP.NET markup code are in the UpdatePanel, else use the Page.ClientScript.RegisterStartupScript() method.

Listing 4

C#
void btnExampleOne_Click(object sender, EventArgs e)
{
    Random rand = new Random();
    string strScript = string.Empty;
    int intRndNum = rand.Next(1, 6);
    int intRes = int.Parse(txtAns.Text);

    string strCtrl = lblMsg.ClientID;

    //multiple control
    //string strCtrl = lblMsg.ClientID + ", " + control2.clientID + "," +control3.ClientID;

    strScript = "HideCtrl('" + strCtrl + "', '3000')";

    if (intRes == intRndNum)
    {
        lblMsg2.Text = "The correct number is: " + intRndNum + ". 
                        You entered: " + intRes + ". Good job!";
        lblMsg.Text = string.Empty;
        divBallon.Visible = true;
    //hide the DIV
        strScript = "HideCtrl('" + divBallon.ClientID + "', '3000')";
    }
    else
    {
        divBallon.Visible = false;
        lblMsg.Text = "The correct number is: " + intRndNum + ". 
                       You entered: " + intRes + ". Please try again.";
    }

    Page.ClientScript.RegisterStartupScript
         (this.GetType(), Guid.NewGuid().ToString(), strScript, true);
}

Conclusion

If you find any bugs or disagree with the contents, please drop me a line and I'll work with you to correct it.
I would suggest downloading the demo and explore it in order to grasp the full concept of it because I might have left out some useful information.

IE, Firefox, Google Chrome, Safari

Tested on IE 6.0/7.0/8.0, Google Chrome, Firefox, Safari

Resources

History

  • 6th June, 2010: First release

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
I have over 10 years of experience working with Microsoft technologies. I have earned my Microsoft Certified Technology Specialist (MCTS) certification. I'm a highly motivated self-starter with an aptitude for learning new skills quickly.

Comments and Discussions

 
GeneralReason for my vote of 5 Well-written and informative. Thank... Pin
BrianBissell13-Sep-11 4:13
BrianBissell13-Sep-11 4:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.