I have decided to build a tool which only includes 2 HTML textboxes (T1&T2). I made their property to “runat=server” by right clicking on these controls using Visual Studio. I will enter an amount in Rupees to T1 and after focus lost from T1, the corresponding Dollar amount want to be displayed in T2. So the code written in the “T1_ServerChange” event is as below. Please recall that 2 textboxes mentioned here are HTML controls (with “runat=server” ) not web controls.
private void T1_ServerChange(object sender, System.EventArgs e)
//Just assume 1Dollar = 45 Rupees
T2.Value = (Int16.Parse(T1.Value) * 45).ToString();
Run the program and enter 1 in T1 and press tab. You will see nothing is happening. You try your own any way to fire a lost focus event. But nothing is happening. So the problem is obvious that the posting to the server side (PostBack) is not occurring. So you want to manually fire a postback to work your code.
So this is one particular situation, in which “_doPostBack” has it’s power. The situation is a webpage with all controls as HTML controls and you want to invoke a code in an event.
So now we are going to manually invoke the postback. Follow the below steps on HTML side
2. Call the above function on the blur event of T1 like onblur = “enablePostBack();”
3. Just paste a linkbutton control on the page(Purpose of this will discuss later)
Now run the program and you will see our tool is working well. The only thing we extra done is manually fired a postback using “__doPostBack”;. So I think you got the situations in which we want to use “__doPostBack”.
4. Please take some precautions.
Before using “__doPostBack” you want to confirm about certain things. After all “__doPostBack” fires a “postback”. Just do the things as below:
Just remove the pasted linkbutton from the above mentioned program and run it. You will try to enter a value in T1 and press tab, then a script error will generate with message as “object expected”. Yes expected objected not got. That’s the problem and the object is “__doPostBack”. ULTIMATELY A POSTBACK WILL ONLY FIRE, IF THERE IS A CONTROL IN THE PAGE WITH A PROPERTY “AUTOPOSTBACK=TRUE”. So just paste a web “TextBox” control and make it’s “autopostback” property to “True”. Then ur program will run without any problem. There is another method also to avoid the above mentioned script error. Just paste a web “linkbutton” control on the page and the program will be perfectly OK. Now you got why I paste a “linkbutton” in our program. But pasting controls to avoid this error is not professional. Do you want to handle it in a professional manner? Just remove the “linkbutton” from the page and add the following to the HTML part.
1. Add 2 hidden controls as below
function __doPostBack(eventTarget, eventArgument)
document.Form1.__EVENTTARGET.value = eventTarget;
document.Form1.__EVENTARGUMENT.value = eventArgument;