ASP.NET Programaticamente adicionando botão com um evento
Eu estou fazendo uma tabela dinâmica que irá adicionar linhas sempre que o botão Adicionar linha é clicado. Estou criando o botão programaticamente e adicionando-o ao cabeçalho da tabela. Abaixo desse botão, e na mesma coluna, haverá também os botões de linha de exclusão.
Estou tendo um problema, quando clico no botão, o evento não está sendo chamado. Estou criando o botão corretamente? Se não, então como faço isso? Se eu sou, sabe qual é o problema?
região Add_Table_Header<code> TableHeaderCell thcOne = new TableHeaderCell(); TableHeaderCell thcTwo = new TableHeaderCell(); TableHeaderCell thcThree = new TableHeaderCell(); TableHeaderCell thcrFour = new TableHeaderCell(); TableHeaderCell thcFive = new TableHeaderCell(); TableCell thcRowAction = new TableCell(); //THIS IS THE COLUMN WITH THE //ADD BUTTON thcOne.Text = "Who"; thcTwo.Text = "Date Started"; thcThree.Text = "Date Ended"; thcrFour.Text = "Causes?"; thcFive.Text = "Result"; //HERE IS WHERE I CREATE AND ADD THE BUTTON Button addRowButton = new Button(); addRowButton.Text = "Add Row"; addRowButton.Click += new EventHandler(this.AddNewRow_Click); thcRowAction.Controls.Add(addRowButton); TableHeaderRow headerRow = new TableHeaderRow(); headerRow.Cells.Add(thcOne); headerRow.Cells.Add(thcTwo); headerRow.Cells.Add(thcThree); headerRow.Cells.Add(thcrFour); headerRow.Cells.Add(thcFive); headerRow.Cells.Add(thcRowAction); table.Rows.Add(headerRow); #endregion protected void AddNewRow_Click(object sender, EventArgs e) { if (ViewState["RowsCount"] != null) { numOfRows = Convert.ToInt32(ViewState["RowsCount"]); GenerateTable(numOfRows); } } </code>
Mais uma vez, o botão aparece, mas não entra no método de evento correto. Obrigado por sua ajuda e tempo :)
By the way quando eu faço declarativamente, tais como:
<code><asp:Button ID="BTNAdd" runat="server" Text="Add New Row" OnClick="AddNewRow_Click" /> </code>
o evento será registrado e funcionará completamente bem.
NEW INFO: Eu tenho um botão delete aparecendo também, eu não registrei nenhum tipo de evento com ele, mas quando eu clico nele, ele faz exatamente a mesma coisa que o botão add row, isso pode ser porque a página mestra ou um diferente fonte está dizendo os botões o que fazer primeiro ou por padrão?
OBRIGADO :)