asp.net server side buttons clicks programatically - c#

i have 2 server side asp.net buttons , i need to automate the buttons clicks.
i.e. After page_load, i need to click button1 and after its results are shown on the page, wait for 10 seconds and click button2 .
i tried the following sample code
protected void Page_Load(object sender, EventArgs e)
{
Button1_Click(Button1, null);
Thread.Sleep(10000);
Button2_Click(Button2, null);
}
protected void Button1_Click(object sender, EventArgs e)
{
changeLabel.Text = "Button1";
}
protected void Button2_Click(object sender, EventArgs e)
{
changeLabel.Text = "Button2";
}
}
i had 2 obeservations (maybe useful):
always Button2_Click(Button2, null); event is the latest when the page is fully loaded (which is obvious).
Page_Load(object sender, EventArgs e) doesnot
hit atall when programatically clicked the button.
Any idea how to achieve the solution.

What you are doing in your example is to call the handlers of button1 and button2's click events, that is not the same as having the user click the buttons, and for the form to postback to the server.
If you want the buttons to click them selves and having the post back to the server you need to add javascript that clicks the buttons for you.
If you want a javascript which hits a button for you after X seconds, i would do something like this:
in your aspx page:
<asp:button ID="Button1" runat="server" ClientIDMode="Static" OnClick="Button1_Click">
</asp:button>
in your javascript files or some block on your page:
<script type="text/javascript">
setTimeout(function(){
document.getElementById("Button1").click();
}, 10*1000); // 10 seconds
</script>
Important to note here is that you have to either set ClientIDMode="Static" on your button, otherwise it might have a very obscure name if you are using master pages, or you can do:
<script type="text/javascript">
setTimeout(function(){
document.getElementById("<%= Button1.ClientID %>").click();
}, 10*1000); // 10 seconds
</script>
if you have the javascript in your .aspx file rather then its own .js file.
ps: if you do Thread.Sleep(X) in an aspx page, you will only make the users browser wait for the X milliseconds more for the page to load, code run before the sleep will not be submitet to the clients browser in the way i think you want it to do.

Button_Click is server event, when invoked from client, browser post the relavent data to server and request of new page content, at that time Page_load is invoked.
if you want to do some thing, encapsulate action to some method and call that method in pre-render. Or other wise, use JavaScript.
protected void Page_PreRender(object sender, EventArgs e)
{
UpdateButton1()
Thread.Sleep(10000); // no need to put sleep
UpdateButton2();
}
protected void Button1_Click(object sender, EventArgs e)
{
UpdateButton1();
}
protected void UpdateButton1()
{
changeLabel.Text = "Button1";
}

Related

How to Delay Calling a function After full page loaded on aspx with c#

Below is my simple source code, I'm just trying to call that function after page load, but what is happening right now is: it calls that function before page load. Page loads for 5 seconds and, after that, it displays label execution.
protected void Page_Load(object sender, EventArgs e)
{
display();
}
void display()
{
Thread.Sleep(5000);
Label3.Text = "done";
}
You should read this document about ASP.NET Page Life Cycle. It actually says what you are trying to do is not possible.
Every code you write in the server side is going to run before the browser renders the page. That means you can not call a function after the browser renders the page, unless you use other approach.
The simplest way you can achieve this is using Javascript and an Ajax call or by using a Timer, which opens a new thread different from the main execution thread. Although, I do not recommend open new threads, because you will lose the control over the execution flow and in a webpage you could end having hundreds of open threads.
Below Code is Working
protected void Page_Load(object sender, EventArgs e)
{
Timer1.Interval = 2000;
Timer1.Enabled = true;
}
protected void Timer1_Tick(object sender, EventArgs e)
{
Label3.Text = "done";
}

How can I invoke a server-side event from jQuery (Sharepoint 2010)?

In my Sharepoint 2010 app, I'm handling most events client-side with jQuery. However, for the saving of data to the Sharepoint list, and the generation of a PDF file with that data, I want to handle that server-side, with C#.
I tried to invoke a C# event this way:
0) Aded an HTML button in my project's *.ascx file:
<button type="button" name="saveData" id="saveData">Save Data</button>
1) Added jQuery to respond to that button being clicked (in the same *.ascx file):
$("#saveData").click(function () {
$('#hiddenSave').trigger('valuechanged');
});
2) Created a hidden element in the server-side C# (in the *.ascx.cs file):
HiddenField hiddenSave = null;
protected void Page_Load(object sender, EventArgs e)
{
base.OnPreRender(e);
hiddenSave = new HiddenField();
hiddenSave.ID = "hiddenSave";
hiddenSave.ValueChanged += new EventHandler(hiddenSave_ValueChanged);
this.Controls.Add(hiddenSave);
}
protected void hiddenSave_ValueChanged(object sender, EventArgs e)
{
GeneratePDF();
}
private void GeneratePDF()
{
;//bla
}
But I never reach the "ValueChanged" event handler; $("#saveData").click() fires, but not hiddenSave_ValueChanged().
So do I need a tweak to this, or a completely different approach? How can I do as much as possible client-side with jQuery, but also run server-side/C# code where necessary, in a Sharepoint 2010 app?
UPDATE
A little more detail, and about additional things I've tried: I'm creating a button on a Sharepoint page dynamically (in C#) in my *.ascx.cs file:
Button btnSave = null;
protected void Page_Load(object sender, EventArgs e)
{
base.OnPreRender(e);
this.Controls.Add(new LiteralControl("<br />"));
btnSave = new Button();
btnSave.ID = "btnSave";
btnSave.Text = "Save the Data";
btnSave.Click += new EventHandler(btnSave_Click);
btnSave.Visible = false;
this.Controls.Add(btnSave);
}
protected void btnSave_Click(object sender, EventArgs e)
{
btnSave.Text = "You clicked me!";
PostTravelData ptd = new PostTravelData();
}
I set it visible at the right time in the client-side jQuery in the *.ascx file:
$('#btnSave').show();
However, clicking the button does not reach the btnSave_Click() event - the breakpoint there is never reached, nor is the button's text changed. Why not?
Even when I don't set the button invisible (comment out the "btnSave.Visible = false;" line), the click handler isn't reached...is Page_Load() too late? Is there an earlier page event I can use that would work?
I tried moving it from Page_Load() to OnPreRender(), too, like this:
protected void OnPreRender(EventArgs e)
{
this.Controls.Add(new LiteralControl("<br />"));
btnSave = new Button();
btnSave.ID = "btnSave";
btnSave.Text = "Save the Data";
btnSave.Click += new EventHandler(btnSave_Click);
//btnSave.Visible = false;
this.Controls.Add(btnSave);
}
...(and OnRender()) but the button doesn't even display...
And, trying a different tack, I commented out the dynamic creation server-side code and tried to attach to a button created in the HTML (*.ascx file):
<button type="button" name="saveData" id="saveData" runat="server" onclick="saveData_Click">Save Data</button>
(by adding the "runat server" and the onclick handler), and then adding this "code-behind" (*.ascx.cs)):
protected void saveData_Click(object sender, EventArgs e)
{
PostTravelData ptd = new PostTravelData();
SaveToList(ptd);
GeneratePDF(ptd);
}
...but there was still no joy in Mudville -- the breakpoint in the handler is not reached.
Yet another attempt was:
In the *.ascx:
<asp:Button runat="server" id="saveData" name="saveData" onclick="saveData_Click" Text="Bla" />
In the code-behind:
saveData.Click += saveData_Click;
The "Bla" button is created, but clicking on it reaches not the breakpoint in the "saveData_Click" handler.
I even adapted some code from here like so:
Button btnSave = null;
. . .
protected override void CreateChildControls()
{
btnSave = new Button();
btnSave.Width = new Unit(150, UnitType.Pixel);
btnSave.Text = "Can you see me?";
btnSave.Click += new EventHandler(btnSave_Click);
Controls.Add(btnSave);
}
...but I still do not reach the "protected void btnSave_Click(object sender, EventArgs e)" handler when I click the button.
Surely there's a way to get a handle on the button server-side and manipulate it (specifically, respond to its click event)...?!?
First of all, as far as I know, there is no such event for input type hidden in a ascx page. If you create the input type hidden with runat server in the ascx code then you'll see that when you try to add this event it's not available. However there are other events like OnClick that you can simulate to get the desired result.

Run the button event handler before page_load

I have a table with all the objects I have in my db. I load them in my Page_Load function. I have a text field and a button that when clicking the button, I want the handler of that click to put a new object with the name written in the text field in the db.
Now, I want that what happens after the click is that the page loads again with the new item in the table. The problem is that the button event handler is run after the Page_Load function.
A solution to this would be to use IsPostBack in the Page_Load or use the pre load function. A problem is that if I would have 3 different buttons, I would have to differ between them there instead of having 3 different convenient functions.
Any solutions that don't have this problem?
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["userId"] == null)
Response.Redirect("Login.aspx");
// LOAD DATA FROM DB
}
protected void CreateObject(object sender, EventArgs e)
{
// SAVE THE NEW OBJECT
}
Maybe you should try loading your data during PreRender instead of Load
protected void Page_Load(object sender, EventArgs e)
{
this.PreRender += Page_PreRender
if (Session["userId"] == null)
Response.Redirect("Login.aspx");
}
protected bool reloadNeeded {get; set;}
protected void CreateObject(object sender, EventArgs e)
{
// SAVE THE NEW OBJECT
reloadNeeded = true;
}
protected void Page_PreRender(object sender, EventArgs e)
{
if(reloadNeeded || !IsPostBack)
// LOAD DATA FROM DB
}
You can check the event target and do what you need then:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
string eventTarget = Page.Request.Params["__EVENTTARGET"];
if(whatever)
{
//do your logic here
}
}
}
Get control name in Page_Load event which make the post back
Use the Page_PreRenderComplete event to retrieve your table. That way your page will always have the most recent data available after all user events have fired.
Why don't you move what you have in the click event into a new method. Then call that method as the first line in your page load?
An old question but I faced the same problem in my C#/ASP.NET Website with master/content pages: a click on a link on the master page should change a query parameter for a gridview on the content page. As you stated the button click event is handled after Page_Load. But it is handled before Page_LoadComplete (see the information about ASP.NET Page Life Cycle), so you can change the page content there.
In my case I solved the problem by setting a session variable in the click event in the master page, getting this variable in the Page_LoadComplete event in the content page and doing databind based on that.
Master page:
<asp:LinkButton ID="Btn1" runat="server" OnCommand="LinkCommand" CommandArgument="1" >Action 1</asp:LinkButton>
<asp:LinkButton ID="Btn2" runat="server" OnCommand="LinkCommand" CommandArgument="2" >Action 2</asp:LinkButton>
protected void LinkCommand(object sender, CommandEventArgs e)
{
HttpContext.Current.Session["BindInfo", e.CommandArgument.ToString());
}
Content page:
protected void Page_LoadComplete(object sender, EventArgs e)
{
string BindInfo = HttpContext.Current.Session["BindInfo"].ToString();
YourBindDataFunction(BindInfo);
}

Clicking a button: disabling and executing the button's handler

On the Button's Click event, ow can you disable the button, and also call its event handler?
I have tried this:
protected void Button1_Click(object sender, EventArgs e)
{
Button1.Enabled = false;
}
This doesn't work in IE, Mozilla, or Chrome.
You could try adding this :
protected void Button1_Click(object sender, EventArgs e)
{
// Do some stuff here
Button1.Attributes.Add("onclick", "javascript:return false;");
Button1.Enabled = false;
}
<asp:Button ... OnClientClick="disableButton(this);" />
<script type="text/javascript">
function disableButton(button)
{
//need to delay a few ms so that the button posts back before being disabled
var buttonToDisable = button;
setTimeout("reallyDisableButton()"), 2);
}
function reallyDisableButton()
{
buttonToDisable.disabled = true;
}
</script>
I assume that your problem is that people are clicking a button several times (because the page it taking a while to load), thus kicking off the event several times and you only want them to be able to do it once. This will disable the button after it posts back preventing accidentally sending multiple concurrent postbacks.

to avoid page refresh during button click event in asp.net

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) // If page loads for first time
{
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString()); // Assign the Session["update"] with unique value
//=============== Page load code =========================
//============== End of Page load code ===================
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Session["update"].ToString() == ViewState["update"].ToString()) // If page not Refreshed
{
//=============== On click event code =========================
Label1.Text = TextBox1.Text;
//lblDisplayAddedName.Text = txtName.Text;
//=============== End of On click event code ==================
// After the event/ method, again update the session
Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
}
else // If Page Refreshed
{
// Do nothing
}
}
protected override void OnPreRender(EventArgs e)
{
ViewState["update"] = Session["update"];
}
}
This is not working for high resolution gradient background.
Consider wrapping your button and the label in an updatepanel control, which uses AJAX to refresh their contents.
The rest of the page will not be reloaded and the action will not affect the browser navigation.
See this page on how an updatepanel control works.
Since you are handling the button click event in server side there has to be a postback to handle it.
If you do not want a post back to happen change the event handling to "client click"
//Heinzi code worked for me just made a small change in OnPreRender event, assign the ViewsState value when its not post back
protected override void OnPreRender(EventArgs e)
{
if (!IsPostBack)
{
ViewState["update"] = Session["update"];
}
}

Categories

Resources