views:

70

answers:

1

I have an ASP Button that I am creating in the CodeBhind of a Control. Here is the code:

Button SubmitButton = new Button();

protected override void CreateChildControls()
{
    SubmitButton.Text = "Submit";
    SubmitButton.Click += new EventHandler(SubmitButton_Click);
}

private void SubmitButton_Click(object sender, EventArgs e)
{
    CustomTabs.CreateNewTab();
}

The Click event won't fire, though. It appears like it does a postback and never hits the event. Any ideas?

+1  A: 

So you have some methods that are not explained, but are you adding the SubmitButton to the page? Somewhere should be:

SomeServerControl.Controls.Add(SubmitButton);

The following works for me (Obviously change namespace):

ASPX

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="VS2010WEBFORMS.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    </form>
</body>
</html>

ASPX.CS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace VS2010WEBFORMS
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        Button SubmitButton = new Button();

        protected void Page_Load(object sender, EventArgs e)
        {
            SubmitButton.Text = "Submit";
            SubmitButton.Click += new EventHandler(SubmitButton_Click);
            form1.Controls.Add(SubmitButton);
        }

        private void SubmitButton_Click(object sender, EventArgs e)
        {
            //Something
        }
    }
}
Dustin Laine
Yes, I am adding it to the page in the CreateChildControls() method, one line after I posted (assumed it wasn't important). I moved the controls into OnLoad() and it works now. But isn't the correct place CreateChildControls()?
mattdell
Are you doing the add like the documentation states, the code that adds the control to the page would be crucial to keep in your post. http://msdn.microsoft.com/en-us/library/system.web.ui.control.createchildcontrols.aspx.
Dustin Laine