I have been unable to get the following code to work. The AddEventClicked event is always null. I have done stuff like this often in the past but for some reason I can't get it to work here. I get no errors. The only thing I can think of is that the problem has something to do with the event not being subscribed to on postback. What am I doing wrong? Thanks.
Code:
public partial class _Default : System.Web.UI.Page { CategoryList List = new CategoryList(); protected void Page_Init(object sender, EventArgs e) { List.AddClickedEvent += new AddClickedEventHandler (List_AddClickedEvent); FindControl("Form1").Controls.Add (new CategoryList()); } private void List_AddClickedEvent(int i){ Response.Redirect( "AddCategory.aspx?ID=" + i.ToString()); } } public delegate void AddClickedEventHandler(int i); public class CategoryList : GridView { public event AddClickedEventHandler AddClickedEvent; public CategoryList() { SqlConnection Conn = new SqlConnection(ConnStr); SqlDataAdapter Adap = new SqlDataAdapter ("select * from Categories order by Name", Conn); DataTable DT = new DataTable(); Adap.Fill(DT); base.AutoGenerateColumns = false; base.DataSource = DT; ButtonField Add = new ButtonField(); Add.CommandName = "AddCategory"; Add.Text = "Add"; base.Columns.Add(Add); BoundField Name = new BoundField(); Name.DataField = "Name"; Name.HeaderText = "Thing Type"; base.Columns.Add(Name); base.DataKeyNames = new string[] { "ID" }; base.DataBind(); base.RowCommand += new GridViewCommandEventHandler(BaseClicked); } } private void BaseClicked(object Sender, GridViewCommandEventArgs Args) { if (Args.CommandName == "AddCategory") { int i = (int)((GridView)Sender) .DataKeys[0].Value; if (AddClickedEvent != null) AddClickedEvent(i); } } }
Comment