I am trying to set the focus on a text box.
SetFocus(txtUserName);
I am not seeing any change on the web page.
What is the difference between .Focus()
and SetFocus()
and what is the functionality of each?
Use the SetFocus method when you want a particular field or control to have the focus so that all user input is directed to this object. To read some of the properties of a control, you need to ensure that the control has the focus. For example, a text box must have the focus before you can read its Text property.
The SetFocus method moves the focus to the specified form, the specified control on the active form, or the specified field on the active datasheet.
You can use .Focus()
on the control itself, or call the Page's SetFocus()
, passing in a reference to the control. Note that you need to pass in the control, not the ID, as that doesn't seem to be supported (at least as of .NET 3.5). See MSDN Page.SetFocus for more.
As to the difference between the methods? They're largely interchangeable, and you should call whichever is more convenient given the objects you have access to - usually calling .Focus()
on the control is easier. See How to Set Focus on ASP.NET Web Server Controls on MSDN.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With