使用这个ASP.Net LoginView,我们希望在网页上加载用户名TextBox时将注意力设置为:
<asp:LoginView
ID="loginViewMain"
runat="server">
<LoggedInTemplate>
<asp:LoginName
ID="loginName"
runat="server"
FormatString="Hello, {0}!<br/><br/> You have successfully<br/> logged onto the staff site." />
<br/>
<br/>
(<asp:LoginStatus ID="loginStatus" runat="server" />)
<br/>
<br/>
</LoggedInTemplate>
<AnonymousTemplate>
<asp:LoginStatus
ID="loginStatus"
runat="server" />
</AnonymousTemplate>
</asp:LoginView>
这是我们试图用来关注用户名文本框的代码隐藏:
Private Sub loginViewMain_Load(sender As Object, e As EventArgs) Handles loginViewMain.Load
Dim objContentPlaceHolder As ContentPlaceHolder
Dim objLoginView As LoginView
Dim objUserName As TextBox
objContentPlaceHolder = CType(Me.FindControl("ContentPlaceHolderBody"), ContentPlaceHolder)
If Not objContentPlaceHolder Is Nothing Then
objLoginView = CType(objContentPlaceHolder.FindControl("loginViewMain"), LoginView)
If Not objLoginView Is Nothing Then
objUserName = objLoginView.FindControl("UserName")
objUserName.Focus()
End If
End If
End Sub
执行确实进入了这个If结构:
If Not objLoginView Is Nothing Then
你能告诉我还需要在这个编码的If结构中添加什么来获取用户名TextBox吗?
答案 0 :(得分:2)
FindControl只搜索一个深度的树级。
尝试使用recursive function代替
例如:
private Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
{
return root;
}
foreach (Control c in root.Controls)
{
Control t = FindControlRecursive(c, id);
if (t != null)
{
return t;
}
}
return null;
}
然后电话会是
objLoginView = CType(FindControlRecursive(objContentPlaceHolder, "loginViewMain"), LoginView);
希望有所帮助。
答案 1 :(得分:2)
您可以在不需要了解LoginView控件的详细信息的情况下执行此操作。而是使用JavaScript查找第一个文本框并关注它。
在代码隐藏文件中添加以下代码:
var script = string.Format(@"
var inputs = document.getElementById('{0}').getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {{
var inp = inputs[i];
if (inp.type.toUpperCase() !== 'TEXT') continue;
inp.focus();
inp.select();
break;
}}", this.LoginView.ClientID);
// register the script
ScriptManager.RegisterStartupScript(this, this.GetType(), "login focus", script, true);
或在VB.NET中:
Dim script = String.Format(
"var inputs = document.getElementById('{0}').getElementsByTagName('input');" &
"for (var i = 0; i < inputs.length; i++) {{" &
" var inp = inputs[i];" &
" if (inp.type.toUpperCase() !== 'TEXT') continue;" &
" inp.focus();" &
" inp.select();" &
" break;" &
"}}", Me.LoginView.ClientID)
' register the script
ScriptManager.RegisterStartupScript(Me, TypeOf(this), "login focus", script, True)