Pregunta

I can't for the life of me figure this out! What I want to do is on the first page load set the button's text and the label's text to the current time. However, when the user clicks the button, only the label's text is updated to the current time and the button's text remains the time of when the page first loaded. I know I can do this with Ajax but i know there is way to do it just using the IsPostBack method. Can anyone help me?

public partial class TestPage : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)
{

    Button1.Text = "Initial Page Load Time: " + DateTime.Now.ToLongTimeString() + ". (Click to update current time in Label)";
    Label1.Text = "Current Time: " + DateTime.Now.ToLongTimeString();





}
¿Fue útil?

Solución

Add a HiddenField to your page, then change your code to;

protected void Page_Load(object sender, EventArgs e)
{
    if ( !Page.IsPostBack ){
        HiddenField1.Value = "Initial Page Load Time: " + DateTime.Now.ToLongTimeString() + ". (Click to update current time in Label)";
    }
    Button1.Text = HiddenField1.Value;
    Label1.Text = "Current Time: " + DateTime.Now.ToLongTimeString();
}

The HiddenField value will be preserved on PostBack so you can set the button text from this.

Otros consejos

Just add this before setting the text:

if (Page.IsPostBack)
   return
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top