问题
Now, this MAY look a duplicate, but it's not. Every solution on the internet shows you how to get focus on the textbox that fired the event.
But what if the user presses tab? The textbox that should have focus is the next one. So we do a workaround and focus on the textbox that have TabIndex higher than the one that fired the event.
But then what if the user presses Shift+tab? Even worse: what if the user clicks on another random textbox?
This is the issue. I don't think a code is required here, because it's a general solution to set focus on textboxes that have autopostback function. If code is required, please ask in the comments.
回答1:
The following will allow you to do what you want:
What we need to do is have js assist with what control will be next, in this case any control that is getting focus (whether it be via tab, shift-tab, click, or whatever control combination leaps out of the text box and onto a different control). By utilizing a WebMethod we can pass this information onto the server for AutoPostBack focus.
WebMethod:
[WebMethod]
public static void set_nextFocus(string id)
{
_toFocus = id;
}
Simple enough, _toFocus is class variable static string _toFocus
, it holds the value of the next control to focus.
Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
//sets focus to the proper control
Page.SetFocus(Page.FindControl(_toFocus));
}
}
JavaScript
in <head>
<script type="text/javascript">
function setFocus(x) {
PageMethods.set_nextFocus(x);
}
</script>
ASP controls
In this example, a TextBox. Note the use of OnFocusIn. It is an expando attribute of the ASP control which will realize there is no server-side definition, and revert to javascript's onfocusin attribute.
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" TabIndex="1"
ontextchanged="TextBox1_TextChanged" OnFocusIn="setFocus(this.id)" >
</asp:TextBox>
Also, in order to use PageMethods you must enable it within the form, like so:
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
回答2:
You can check the __EVENTTARGET
property of form which will tell you the textbox name from which the event has been raised.
Scenario, say I have two textboxes named TextBox1
and TextBox2
for both AutoPostBack
set to true
and hooked up textChanged
event to single handler TextBox1_TextChanged
. You can have below code and set the focus back to the specific textbox control
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
string target = Request.Form["__EVENTTARGET"];
if (target == "Textbox2") //conrol name should be exact
{
Page.SetFocus(this.TextBox2);
}
}
来源:https://stackoverflow.com/questions/32383998/set-focus-back-to-the-proper-textbox-after-autopostback-function-page-setfocus