Introduction
In this trick, we are regaining the focus on the same control which did the postback, after the page loads again in a simple way.
Background
This is general that after postback, we lose the focus on the control which did the postback.
There are few available discussions to solve this, but almost all are using JQuery and advanced code, but this one is a simple one to demonstrate how to do it easily.
Using the Code
First take three textboxes in your page, and generate "Ontextchanged
" event for each of them.
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"
ontextchanged="TextBox1_TextChanged" TabIndex="1"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server" AutoPostBack="True"
ontextchanged="TextBox2_TextChanged" TabIndex="2"></asp:TextBox>
<asp:TextBox ID="TextBox3" runat="server" AutoPostBack="True"
ontextchanged="TextBox3_TextChanged" TabIndex="3"></asp:TextBox>
After that, inside each event created for
textbox
, write the code:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Session["event_controle"] = ((TextBox)sender);
}
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
Session["event_controle"] = ((TextBox)sender);
}
protected void TextBox3_TextChanged(object sender, EventArgs e)
{
Session["event_controle"] = ((TextBox)sender);
}
protected void Page_PreRender(object sender, EventArgs e)
{
try
{
if (Session["event_controle"] != null)
{
TextBox controle =(TextBox) Session["event_controle"];
controle.Focus();
}
}
catch (InvalidCastException inEx)
{
}
}
Points of Interest
Certain modifications are needed, but you can use this concept.
History
- 26th October, 2013: Initial version