Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Set Focus on the Same Control after Postback using C# ASP.NET

4.84/5 (11 votes)
26 Oct 2013CPOL 62.1K  

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.NET
<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:
C#
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);
       }
       //then copy the pre-render code as given below,
       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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)