开发者

asp.net Login control: what's wrong?

开发者 https://www.devze.com 2023-02-20 03:31 出处:网络
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:

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;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号