开发者

Having issues getting around the scope of my event handler(ASPX .NET 3.5)

开发者 https://www.devze.com 2023-03-19 03:33 出处:网络
I\'ve been trying to template control panels in my site so I can take a panel and populate it fully. I\'m good up until the point where my event handling needs to access functions on my page. My curre

I've been trying to template control panels in my site so I can take a panel and populate it fully. I'm good up until the point where my event handling needs to access functions on my page. My current test will take me to a login redirect page. So how can I get this event handler to perform a redirect?

public class DebugButton : Button
{
   开发者_开发知识库 public string msg;
    public DebugButton()
    {
        this.Click += new System.EventHandler(this.Button1_Click);
        this.ID = "txtdbgButton";
        this.Text = "Click me!";
        msg = "not set";
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        msg = "Event handler clicked";
    }
}

*on the Page*

protected void Page_Load(object sender, EventArgs e)
DebugButton btnDebug = new DebugButton();
PnlMain.Controls.Add(btnDebug);

Really appreciate the help. Thanks!


To do a redirect you can use:

Note: Assuming that your login page is named login.aspx and it is located in root folder of your website.

protected void Button1_Click(object sender, EventArgs e)
{
    Response.Redirect("~/login.aspx");
}

or

protected void Button1_Click(object sender, EventArgs e)
{
    Server.Transfer("login.aspx");
}


If you want the event to have access to the page, then the page needs to subscribe to the click event.

Aka:

on the Page

protected void Page_Load(object sender, EventArgs e)
{
    DebugButton btnDebug = new DebugButton();
    btnDebug.Click += new System.EventHandler(Button1_Click);
    PnlMain.Controls.Add(btnDebug);
}

protected void Button1_Click(object sender, EventArgs e)
{
    // access whatever you want on the page here
}


I just found out that that System.Web.HttpContext.Current will get me the current context of the page. So long as the custom class is part of the app(this one is in the apps folder of course) I'm good to go. Heres a sample of my quick TestTemplate that I used to make a custom button.

public class TestTemplate : Button
{
    public TestTemplate()
    {
        this.Text = "Click Me";
        this.ID = "btnClickMe";
        this.Click += new System.EventHandler(this.EventHandler);
        //
        // TODO: Add constructor logic here
        //
    }

    public void EventHandler(object sender, EventArgs e)
    {
        //System.Web.HttpContext.Current.Server.Transfer("Default.aspx");
        System.Web.HttpContext.Current.Response.Write("This is a test!");
    }
}
0

精彩评论

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