user1940488
user1940488

Reputation: 11

change label text programmatically in c# web forms

I searched the internet over and over, and this seems to be very straightforward, but somehow it's not working.

I'm trying to create a web forms application in C#. Button1 is supposed to download a lot of data from a website, and I want to Label1 to display "downloading" while the code in Button1 runs, and "done" after the code finishes, but Label1 is not changing at all after button click.

code is below:

protected void Button1_Click(object sender, EventArgs e)
        {
            Label1.Text = "downloading";
            //code for downloading data
            Label1.Text = "done";
        }

Upvotes: 1

Views: 9578

Answers (4)

AbdusSalam
AbdusSalam

Reputation: 440

If you want to change text from downloading to done then you may do this:

Label lbl = (Label)this.FindControl("Label1");
                    if (lbl != null)
                    {
                        lbl.Text =  "done";
                    }

Upvotes: 0

Steven H
Steven H

Reputation: 39

I don't know if this will still be helpful since the post is rather old, but I stumbled upon the question while searching for an answer to a question of my own.

Just use the Label1.Update() function after you change the label's text.

Upvotes: 0

Irfan Shaikh
Irfan Shaikh

Reputation: 1

protected void Button1_Click(object sender, EventArgs e)
{
    Label1.Text = "downloading";
    //code for downloading data
    Label1.Text = "done";
    Label1.Refresh;
}

Upvotes: -1

Matt Varblow
Matt Varblow

Reputation: 7891

That's not going to work. That's all server-side code. The updated HTML is not sent back to the browser until after the Button1_Click handler is finished executing. So the browser will only see the "done" label text. Never the "downloading" text.

The easiest way to achieve your desired effect is to use client-side javascript (maybe using jquery) to update the label text to "downloading" before you submit the form. You can put your client-side javascript in the OnClientClick property of the asp.net button. The server-side code can then download the data and change the label text to done.

Upvotes: 2

Related Questions