Things are a little bit trickier for textboxes. Because for buttons, we have a rather clear correspondence between client-side event and server-side event, which are OnClientClick and OnClick, accordingly. When it comes to textboxes, we have to use onchange(for client side) and OnTextChanged(for server side), and the client-side handler has to be added dynamically, which are neither convenient nor intuitive. However, this is not the only complication we are facing here.
1. First, for the client-side button click event, we can use the following code to ensure the postback will or will not be executed. For example:
btn_Find_Planer.OnClientClick = String.Format(@"return Find_Empno('tbx_PlanerEmpno', '{0}', '{1}', '{2}', false);", tbx_PlanerName.ClientID, tbx_PlanerExt.ClientID, tbx_PlanerDept.ClientID);
Inside Find_Empno function we can decide whether to perform the postback or not, and if we do choose to postback, we know for sure the event will be correctly handled in its server side handler, btn_Find_Planer_Click, right after the client side handler finishes it job.
When it comes to textboxes, I have to do it in a similar, but different way. For example:
tbx_PlanerName.Attributes["onchange"] = String.Format(@"Find_Empno('tbx_PlanerEmpno', '{0}', '{1}', '{2}', true);", tbx_PlanerName.ClientID, tbx_PlanerExt.ClientID, tbx_PlanerDept.ClientID);
Note that there is no return keyword. For some reason, if I add the return statement, the postback won't happen at all. If I get rid of the return keyword, then the postback will be directed to its server side handler, tbx_PlanerName_TextChanged, as I desire. (I haven't quite figured out the reason behind it yet...)
2. Of course, there is another catch. I would have to set the AutoPostBack property to true for the textbox if I want to post back to server side right away, which, by the way, will lead to another error. The browser would complain that an object is required here. I thought it might be caused by the code .NET appends automatically:
setTimeout('__doPostBack(\'ctl00$ContentPlaceHolder1$tbx_PlanerName\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;"
The way I solve the problem is to add the reference to the resource WebForms.js as follows:
this.Page.ClientScript.RegisterClientScriptResource(typeof(System.Web.UI.Page), "WebForms.js");
Anyway, there are so many details that are driving me crazy here...
reference: http://www.cnblogs.com/Truly/archive/2007/07/07/809576.html
沒有留言:
張貼留言