开发者

Why isn't the value of the textbox changing when I click the button?

I would like that each the button is pressed, the textbox shows the time. How to achieve this? Now the page is refreshed and the code is called, but the 开发者_开发技巧value of the textbox does not change.

NOTE: I of course don't need completely new code achieving just that. I need to be able to do it in the code behind file of an asp file.

protected void Page_Load(object sender, EventArgs e)
    {
        TextBox t = new TextBox();

        t.ID = "time";


        Button submit = new Button();
        submit.Text = "Update";
        submit.UseSubmitBehavior = true;

        form1.Controls.Add(t);
        form1.Controls.Add(submit);
        t.Text = DateTime.Now.ToString();

    }


Update:
Try this approach, creating the child controls in the wrong place leads to weird effects like you see above, because the event order is all off, e.g. the page's load is firing before the control's Init. The CreateChildControls happens in the page's PreRender event, you can see here for a full breakdown. For a reference of when ViewState's loaded: this is a better view.

private TextBox t;

protected override void CreateChildControls()
{
  base.CreateChildControls();

  t = new TextBox {ID = "time"};
  Button submit = new Button {Text = "Update", UseSubmitBehavior = true};
  Form.Controls.Add(t);
  Form.Controls.Add(submit);
}

protected void Page_Load(object sender, EventArgs e)
{
  t.Text = DateTime.Now.ToString();
}

Since ASP.Net only uses one form by default, page has a Form property you can use.


From Dynamic Web Controls, Postbacks, and View State:

If we need our dynamically added controls to maintain their view state it is paramount that these controls be added before the Load View State stage. That is, these controls must exist within the page's control hierarchy before the view state is loaded. There's only one stage before Load View State - Initialization. That means, if we want our dynamic controls to persist view state we must add them to the control hierarchy in the page's Init event.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜