TextBox Focus Question

J

Joe Delphi

Hi,

I have more experience working with Windows.Forms than with WebForms
and sometimes it trips me up.

When my page loads, I want a particular textbox to have the focus. I
am attempting to do it using logic like this:

if TextBox1 CanFocus then
TextBox1 Focus()
end if

But the compiler does not like that because the web version of the
TextBox class does not have CanFocus or Focus()

How do I set the focus to the desired textbox?


JD
 
P

Patrick Olurotimi Ige

Joe you can use this in page_load
and make sure you import "Imports System.Text
and txtAge is the ID of your textbox

Dim strBuilder As StringBuilder = New StringBuilder
strBuilder.Append("<script language='javascript'>")
strBuilder.Append("document.getElementById('txtAge').focus()")
strBuilder.Append("</script>")
RegisterStartupScript("Focus", strBuilder.ToString)

Hope it helps
Patrick
 
G

Guest

Hi Joe,

First of all you should understand that web application is different from
desktop application. The web application runs on a client-server mode. Any
web server control only exists on server-side. Once rendering to client-side,
it is destroyed. And corresponding html component is shown on client-side.
Actually a 'focus' event occurs on client-side. So client-side JavaScript
code can be used to conduct focus and other events.

Following code snippet shows how to set TextBox focus:

String strFocus = "<script>document.all." + txtbox.ID + ".focus();</script>";
Page.RegisterStartupScript("focusTextBox", strFocus);

HTH

Elton Wang
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top