开发者

disable "cause validation" for dynamically created buttons

I am creating the same button twice: once on Page_Load, and another on: Page_PreRender. I expected to see the same behavior, however, the buttons created on Page_PreRender doesn't work the way intended. (i.e. property "causeValidat开发者_如何学Goion" remains true).

"I want to disable "causeValidation" for the button in page_preRender, and i want it there in PreRender. Also, I want the Button_Click function to execute for both buttons, currently it does only for button created on "Page_load" ".

I am looking for a solution or an explanation for this behavior.

Thank You.

Take a look at the code:

protected void Page_Load(object sender, EventArgs e)
    {            
        form1.Controls.Add(GetButton("Button1", "Click"));
    }

    protected void page_PreRender(object sender, EventArgs e)
    {
        form1.Controls.Add(GetButton("Button3", "Click"));
    }

    private Button GetButton(string id, string name)
    {
        Button b = new Button();
        b.Text = name;
        b.ID = id;
        b.CausesValidation = false;
        b.Click += new EventHandler(Button_Click);
        b.OnClientClick = "ButtonClick('" + b.ClientID + "')";
        return b;
    }

    protected void Button_Click(object sender, EventArgs e)
    {
        ClientScript.RegisterClientScriptBlock(this.GetType(), ((Button)sender).ID, "<script>alert('Button_Click');</script>");
        Response.Write(DateTime.Now.ToString() + ": " + ((Button)sender).ID + " was clicked");
    }

and here is the javascript:

<script type="text/javascript">
    function ButtonClick(buttonId) {
        alert("Button " + buttonId + " clicked from javascript");
    }
</script>

Update: let me add this: Both buttons execute the client's script. This means that buttons are created. "see function GetButton() ".

Also, the reason why i have the button created "on preRender" instead of "on Page_Load" is that: if i have a form used to enter data into a table dynamically, and i add the data on button click, the the page will PostBack first, then execute the event handler, (i.e the data is added to the table but will show on NEXT postBack). So, PreRender is used to show the table AFTER it is updated by the button_click event.

I hope this addition is useful


disable "cause validation" for dynamically created buttons

As you see from this image, that represents asp.net page life cycle (copied from MSDN), Event Handling precedes PreRender. So, in order to fire Button_Click the button itself has to be created before the Event Handling. Page PreInit is a preferred place to add dynamic controls.

you can see it yourself, just add breakpoints at Page_Load, Page_PreRender, Button_Click. notice the order there are triggered?


Check asp.net page lifecycle: events are handled after page load and before PreRender.

ASP.NET cannot handle an event involving a control that does not yet exists.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜