link button on Master Page with Click Event on Content Page Stack-overflow Exception

僤鯓⒐⒋嵵緔 提交于 2020-01-16 07:39:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!