2016-12-13 111 views
0

我知道FindControl但我的按钮是在一个LoginView控件内的Login控件,下面是我的代码,但它不工作!使登录按钮在asp.net默认

Login log = LoginView1.FindControl("Login1") as Login; 
Button logButton = log.FindControl("LoginButton") as Button; 
this.Form.DefaultButton = logButton.UniqueID; 

钍错误我得到的是不设置到对象的实例

对象引用。

+0

'FindControl'只着眼于眼前的孩子。你需要递归导航所有的孩子,孩子的孩子等,找到你要找的控件。 – ps2goat

+0

我其实在这个网站上有这样的例子:http://stackoverflow.com/a/19313306/2084315 – ps2goat

+0

你可以发布aspx标记吗? – TrevorBrooks

回答

0

FindControl只看直接的孩子。你需要递归导航所有的孩子,孩子的孩子等,找到你要找的控件。

public Control MyFindControl(Control parent, string controlIdToFind) 
{ 
    foreach(Control c in parent.Controls) 
    { 
     Control found = MyFindControl(c, controlIdToFind); 
     if (found != null) 
     { 
      return found; 
     } 
    } 

    // control not found. 
    return null; 
} 

然后更改您的代码:

Button logButton = (Button) MyFindControl(LoginView1, "LoginButton"); 

if (logButton != null) 
{ 
    this.Form.DefaultButton = logButton.UniqueID; 
} 
+0

可能有一些额外的用户控件的工作,但这是基本的方法 – ps2goat

+0

谢谢这看起来不错,但这仍然只看LoginView,而不是在LoginView里的按钮所在的地方,或者我错过了一些东西? – zaidasp