问题
I am trying to connect an asp link button on a master page to its click event on the content page. I followed descriptions from various online posts, but when I try running the page, I get a Stack-overflow exception in the get{} set{} part of the link button property. I could not find anyone else with this problem, mainly because I don't know what the actual problem is. Here are some bits of my code:
Master Page:
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="mySite.master.cs" Inherits="mySite1.mySite" %>
<asp:LinkButton id="myLink" Text="Home" runat="server"/>
Master Page CS:
public LinkButton myLink
{
get
{
return myLink; //FAILS HERE IF I COMMENT OUT THE SET.
}
set
{
myLink = value; //THIS IS WHERE IT FAILS!
}
}
Index.aspx.cs:
protected void Page_Init(object sender, EventArgs e)
{
if(Master.myLink != null)
Master.myLink.Click += new EventHandler(MainTabBtn_Click);
}
protected void MainTabBtn_Click(object sender, EventArgs e)
{
//DO STUFF
}
Index.aspx:
<%@ Page Title="MySite" Language="C#" MasterPageFile="~/MySite.Master" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MySite1.Index" %>
<%@ MasterType VirtualPath="~/MySite.Master" %>
Anyone can tell from this what the problem is? Thanks for your help,
Marvin
回答1:
You assign a value to the myLink property which assigns it to the myLink property (myLink = value
) which assigns it to the myLink property... in an infinite loop - the classic stack overflow exception. Find the control on the master page instead.
回答2:
Did you try this?
protected void Page_Init(object sender, EventArgs e)
{
LinkButton myLink = (LinkButton)Master.FindControl("myLink");
myLink.Click += new EventHandler(MainTabBtn_Click);
}
回答3:
You should change
public LinkButton myLink
to
public LinkButton MyLink
Change the property name or the intern variable it is containing, any of those will be fine, because other way you will be calling the property myLink
, that the value is myLink
, that the value is myLink
, etc etc
来源:https://stackoverflow.com/questions/30579906/link-button-on-master-page-with-click-event-on-content-page-stack-overflow-excep