Matt Dell
Matt Dell

Reputation: 9541

C# Button Not Firing?

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?

Upvotes: 2

Views: 1357

Answers (1)

Dustin Laine
Dustin Laine

Reputation: 38543

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">
<html xmlns="http://www.w3.org/1999/xhtml">
<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
        }
    }
}

Upvotes: 2

Related Questions