updating Textbox.text in serverside code asp.net - asp.net

I have a textbox in my default.aspx page that I want to update it's text property in an event handler but the change does not take place after executing the code .
void _gsc_Task_Completed(object sender, TaskEventArgs e)
{
TextBox1.Text = "New Value";
}
How ever , if I do this on the click event of a simple button the textbox.Text value
changes.
what is the difference between a custom event handler like _gsc_Task_Completed and a simple button click event ?

Text box is a server side control. when you change the text this work(change text) is client side so the event not firing. but when i click on a button the page is going to server and back so the event is firing.

You need to consider the page lifecycle: http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx
Either your event handler is being called to early (and clobbered by whatever is brought back from the client) or it is being called after the control was already rendered.
If I were you I'd put a breakpoint there as well as normal handlers for page onInit, onLoad, etc. See what order that handler is called (if at all) and what is below it on the callstack.

Related

Detecting target of postback early in page_load to exit so click handler can run

I have a webforms page with a gridview and several other buttons. In debugging, I've noticed all the binding to gridview executes during postback in the Page_Load sub. Only after this is all done do the click handler(s) get invoked and in my case the handler does a Response.Redirect to another page.
So, I found this on SO: Run the button event handler before page_load.
It suggests the possibility of detecting the target of the postback during page_load and I was thinking of exiting the page_load in this case and letting the button click handler load a new page (i.e. avoiding all the wasted building and formatting of the gridview.
Here is a snippet from my Page_Load:
If IsPostBack Then
Dim targetOfPostBack As String = Request.Params("__EVENTTARGET").ToString()
End If
During PostBack the __EVENTTARGET is always an empty string rather than something suggesting the "add" button I clicked (i.e. ctl00$MainContentPlaceHolder$btnAddEvent). Trapped here:
The OP on SO above is expressing this same approach in C# while my implementation is VB.Net. What am I doing wrong?
On your asp button try setting UseSubmitBehavior="False"
Use the UseSubmitBehavior property to specify whether a Button control uses the client browser's submit mechanism or the ASP.NET postback mechanism. By default the value of this property is true, causing the Button control to use the browser's submit mechanism. If you specify false, the ASP.NET page framework adds client-side script to the page to post the form to the server.
When the UseSubmitBehavior property is false, control developers can use the GetPostBackEventReference method to return the client postback event for the Button. The string returned by the GetPostBackEventReference method contains the text of the client-side function call and can be inserted into a client-side event handler.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.usesubmitbehavior(v=vs.110).aspx
You can write a client side script to redirect the page thus avoiding the postback all together. Set "OnClientClick" (Asp.NET Button) or "OnClick" (HTML Buttom) property and then simply return false.
Eg:
Script:
function RedirectToURL()
try {
window.open("<Your URL Here>", "_self", "menubar=0,resizable=
} catch (e) {
}
return flase;
}
Button :
<input type="button" id="btnToggleConfig" onclick="RedirectToURL()" runat="server"
value="Click here to Goto Link" />
This is the ASP.NET page life cycle at work: http://msdn.microsoft.com/en-us/library/ms178472(v=vs.85).aspx
A few options:
check out this post for _EVENTTARGET being empty:
__EVENTTARGET is empty on postback of button click
Handle the redirect on the client side (if possible)
Only fill the gridview only once on page_load (If Not IsPostback) if that's an option
If you're only worried about the gridview being recreated and eating up some 'processing power' or time, depending on size, users, etc, may not be a big issue, so could leave as-is.

ASP.NET drop down selected index not changed event

There is an event onSelectedIndexChange for DropDownList in ASP.NET which triggers when a selected index is changed for a dropdown.
I have encountered a situation where I need to trigger similar kind of event when SelectedIndex of DropDown does not change upon selection.
I am totally puzzled what to do in such a case?
Any help/references will highly be appreciated.
Thank you.
I think that is normal. The event is SelectedIndexChanged and you said you selected the same item that was previously selected before. So the index remains the same, not changed, and the event won't fire. May be you look at OnClick.
The issue is that you have not changed the index when you clicked the second time, so the dropdown is still waiting for you to change it
Assuming you have another server-side control on your page that causes a postback, you could write a routine in the postback event for the other control that compares the current selection with the previous selection and fire a custom-event (or the routines you want to happen) if the value has not changed.
That said, I have to imagine there's an easier way to accomplish the overall goal you're trying to achieve, but you'll have to be a little more specific in your question.
UPDATE
I have to assume that you are using the value from the dropdown when you are processing the form. Why not start off with the dropdown hidden and the linkbutton shown? Just select a default from the dropdown list and allow the user to change it as needed.
Here's a fiddle showing that behavior: http://jsfiddle.net/rjaum/
That's fairly easy.
You can achieve this using javascript/jquery/server side code etc. Assuming user does click the control.
Something like this on pageLoad
PageLoad()
{
YourDropDownList.Attributes.Add("onclick","javascript:CallHelloWorld();return false;");
}
Then on server side you can decorate a method with WebMethod attribute
[WebMethod()]
public static string HelloWorld()
{
return "Hello foo";
}
On your client side aspx you can use jQuery to call your webmethod
<script language="text/javascript">
function CallHelloWorld()
{
// Call HelloWorld webmethod using jQuery $.ajax
}
</script>
Edit
You can use a radiobutton list instead of dropdownlist. That way, on client side you can check the event when the radio button is clicked that it is checked or not (if its checked fire your event).
Edit
Also try looking at this thread if you want to use dropdown list specificallyFire event each time dropdown list is selected with JQuery
assign an a event handler to the selected index changed event and set autopostback to true
in markup
or code behind
mydropdownlist.SelctedIndexChanged += NameOfMethod
the handler is then defined like this
protected void NameOfMethod(object sender, EventArgs e)
{
//your code here
}
update
by definition the selectedindexchanged event would only fire when the index changes. if you want to force the postback that will require some javascript. here is an example of how to do that with jquery
$(function() {
$('select').change();
});

Button click event handler before page load

I will describe my problem in simple way so it's not exactly what I'm trying to do but the idea is the same.Here is the problem:
I create dynamic buttons from code behind.I get some id from query string,create button with that id ,dynamic add event handler to click event,and add button to placeholder.I store the list of id-s in session and in page load method recreate these buttons and add to placeholder.One of the id-s is CurrentId and it's also stored in session.Buttons click handler do something like this
Button b=(Button)sender;
Session["CurrentId"]=Convert.ToInt32(b.ID);
In page load when I create buttons I want to set button text property different from others if id==Convert.ToInt32(Session["CurrentId"]) when list of id-s are gotten from session.But problem is that click event handler is called after page load,and when I create buttons in page load ,CurrentId in session hasn't been channged by click event handler.Can you suggest any solution to this situation?
It looks like you are attempting to update the buttons you have dynamically created after the click event has fired. Why not just change the button text within the click event as you have described?
i.e.
protected void button_Clicked(object sender, EventArgs e)
{
((Button)sender).Text = "Custom text for active button";
}
Also, you can always update the buttons on the PreRender event which occurs after the control click events but before the controls are served back down to the client.

Conditionally trigger a full page postback from a link button inside an update panel

How do I conditionally trigger a full page postback from a link button inside of an update panel?
I have a custom control that contains its own updatepanel with a link button nested inside of it. When the link button is pressed I want its event handler to have the option of either letting the control update as normal or doing a full postback on the page.
Here is the control hierarchy:
Page
Custom Control
UpdatePanel
LinkButton
Event handler Pseudo code:
LinkButton Click Handler Begin
If is a partial post back AND a full postback is needed
Page.DoFullPostback
End If
End Handler
Note: I aways need the partial postback to happen. I was considering injecting a __DoPostback in the controls markup but this seems hacky to me.
Thanks for your help!
Sorry, I'm not familiar with the VB, so my example source will be written in C#:
protected void btnLink_Click(object sender, EventArgs e)
{
bool isAsync = ScriptManager.GetCurrent(Page).IsInAsyncPostBack;
bool postBackIsNeeded = true;
if (isAsync && postBackIsNeeded)
{
ScriptManager.GetCurrent(Page).RegisterPostBackControl(btnClick);
string postback = Page.ClientScript.GetPostBackEventReference(
btnClick,
string.Empty
);
ScriptManager.RegisterStartupScript(
btnClick,
btnClick.GetType(),
"postback",
postback,
true
);
}
}
The main idea is to change the type of postback of your LinkButton control. If neccessary it should be changed to full postback instead of partial during the async postback event. Right after this, another postback script should be generated and it should be executed as soon as the page will be returned to client.
And the last thing - use loop detection condition (if (isAsync && postBackIsNeeded) in my case) otherwise postback will be infinite.
The easiest approach is to create a hidden button somewhere on your page, outside of any UpdatePanels. When you need to do a full postback, use JavaScript to either click the button or issue __doPostback() to it. You can achieve a partial postpack programmatically in JavaScript by calling __doPostback() on an UpdatePanel itself, or to a button inside one.

UserControl events not working for first time

I am calling my user control in a web page dynamically.
For the first time when I click the button on user control, the event is not firing. When I click the same for a second time, the events are firing..
Can anyone help me?
Sounds like the hookup to the button OnClick event is not occurring on every page load, which is required.
Can you guarantee that the hookup is being performed when you add the control and after a poastback to the page? I always put my event hooks in the Page_Init or Page_Load event handlers and outside of any Postback check. Try putting a breakpoint on the Handler hook up and see if the breakpoint gets "hit" twice.
An event hookup for a button would look similar to:
protected void Page_Load(object sender, EventArgs e)
{
btnSearch.Click += new EventHandler(btnSearch_Click); // breakpoint on this line
}
The client id of the control is derived from the ID of all containing controls that are marked with the INamingContainer interface. So, make sure that ALL controls in the hierarchy have a fixed ID.
For example if you have a Button control inside a Repeater, the ID of the button and the repeater are concatenated to make the client ID for the button. So both the repeater and the button should have the same ID across postbacks.
You can compare the HTML for the first request with the HTML of the second request to quickly determine if this is the problem.
Assign an ID for your dynamically created control -- otherwise no events will be fired.
Are you waiting for the download of full page before pressing the button?
The events are javascript functions hidden by ASP.Net in the page, that maybe not present at the time of your clicking.

Resources