This is the question I received from developers on how to set the focus to an ASP.NET control from server side. Because once page is posted back to server or when request sent to server, from the response we need to set the focus to some x control on the page from server side.
There are requirements like this. For example, we have multiple panels on the page and when you saved the data successfully of a panel then you need to show the user the panel they submitted with some successful message instead of showing them the top section of page always. :) Otherwise, user always needs to scroll down to the panel where he edited the changes and see whether the data saved successfully or not. An user experience problem.
Usually, the way the developers will do is, catch the control in client side either using javascript or jquery, then they will write logic to set the focus to it. But it's not needed. We can simply use the existing functions available in ASP.Net and C# and implement the behavior without any pain. See below example on how to do that.
C# language by default providing some options to set the focus to an ASP.NET control on the page. There are two ways to do that.
- You can directly use Focus() method to set focus to a control.
tbName.Focus(); - You can use the Page object function named "SetFocus" to set the focus to a control as shown below.
Page.SetFocus(tbName);
Note: Assuming "tbName" is the textbox control id on the page.
So, by using any of the above ways we can set the focus to a control from server side code itself. I hope this will help you. Please provide your comments on it.
NOTE: Don't try to set the focus to the control when it is in disable mode or invisible. This will give some problems in the client side.