Tuesday, September 17, 2013

ASP.NET: Simulate a Button Click in Code Behind

In this blog, I will go over how you can simulate a button click postback.  By using the RaisePostBackEvent()  method.  Many of you probably want to do this because you wanted to refresh your GridView by faking a postback.  As you will see the two methods presented on this blog does not perform an actual postback, even though it behaves like it does.


Mark Up

    <form id="form1" runat="server">
<div>

<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />

</div>
</form>


Code Behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication2
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.RaiseEvent(this, new EventArgs());
if (!Page.IsPostBack)
{
this.Button1_Click(this, new EventArgs());
}
}

protected void RaiseEvent(object sender, EventArgs e)
{
this.RaisePostBackEvent(Button1, " ");
}

protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("You've clicked " + Button1.Text + " ");

if (Page.IsPostBack)
{
Response.Write("this is a post back");
}
else if (!Page.IsPostBack)
{
Response.Write("this is not a post back");
Response.Write("<br/>");
}
}
}
}


After you run the code you will find out that both ways of doing this does not cause a post back event.

No comments:

Post a Comment