Set focus to textbox in ASP.NET Login control on p

2019-01-25 04:39发布

I am trying to set the focus to the user name TextBox which is inside an ASP.NET Login control.

I have tried to do this a couple of ways but none seem to be working. The page is loading but not going to the control.

Here is the code I've tried.

SetFocus(this.loginForm.FindControl("UserName"));

And

TextBox tbox = (TextBox)this.loginForm.FindControl("UserName");
if (tbox != null)
{    
  tbox.Focus();
} // if

9条回答
我命由我不由天
2楼-- · 2019-01-25 05:06

I've been struggling with this too and I've found a solution that seems to work very well even with deeply nested controls (like AspDotNetStorefront a.k.a. ASPDNSF uses). Note the following code called from the Page_PreRender routine. I knew the name of the TextBox I wanted to give focus to and so I just called FocusNestedControl(Me, "UserName"). I just used Me here because all the routine needs is a parent of the control to get focus; it doesn't matter which parent.

    Public Function FocusNestedControl(ByVal ParentControl As Control, ByVal ControlNameToFocus As String) As Control

        If ParentControl.HasControls Then
            For Each childCtrl As Control In ParentControl.Controls
                Dim goodCtrl As Control = FocusNestedControl(childCtrl, ControlNameToFocus)
                If goodCtrl IsNot Nothing Then
                    goodCtrl.Focus()
                    Return goodCtrl
                End If
            Next
        Else
            If ParentControl.ID = ControlNameToFocus Then
                ParentControl.Focus()
                Return ParentControl
            End If
        End If

        Return Nothing
    End Function
查看更多
萌系小妹纸
3楼-- · 2019-01-25 05:06

My problem arrized when i moved login control to a custom control and tried to find UsernameTextBox at the OnInit() method. OnInit of a control is executed before OnInit of Page and this is why no Form control have been created.

I moved the call to UsernameTextBox to the OnLoad function and it worked correctly.

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-01-25 05:12

You can set focus directly on LoginControl and it will automatically set focus on first field in control. In your case:

this.loginForm.Focus();

More info on MSDN: How to: Set Focus on ASP.NET Web Server Controls

查看更多
登录 后发表回答