asp.net Login control: what's wrong?
I'm working on ASP.NET app and in the master page C# code I want to access the login control, so I have the following code:
Login login = new Login();
login = this.Master.FindControl("login") as Login;
But, I get exception " Object reference not set to an instance of an object" when this line
login = this.Master.FindControl("login") as Lo开发者_运维技巧gin;
is executed.
I can't see what can be wrong...
Thanks.
If I read your question correctly, you have a master page and you are trying to use FindControl to find a control named login on that page. If so, then you should be doing this:
login = this.FindControl("login") as Login;
because this:
login = this.Master.FindControl("login") as Login;
would be looking for the control in the master page that your current master page is nested in.
In other words, that last line of code would work if you had a nested master page - for Example Site.Master, and also had a nested child MasterPage named Section.Master IF the login control was in the Site.Master and the code snippet were in the Section.Master.
(Hopefully that made sense.)
If the code mentioned above is in the master page, then try removing the Master portion of the code...
for example
login = this.FindControl("login") as Login;
The reason why this would work is because the current master page, is not embedded within another Master page. Therefore, you'll get an "object not set" error when trying to access the master's Master page (i.e. this.Master.FindControl())
Just wondering, if this is the case, is there a reason why you can't access the control by its name?
You should be able to reference the login control directly by the ID element.
In markup:
<asp:Login runat="server" ID="MainLogin" ....... />
In code-behind:
MainLogin.Visible = false;
精彩评论