ASP.NET编程添加按钮与事件 [英] ASP.NET Programmatically adding button with an event
问题描述
我想提出一个动态表,只要单击添加行按钮,将添加行。
我以编程方式创建按钮并将其添加到表头。
低于该按钮,并在同一列上会有删除行按钮太
I am making a dynamic table that will add rows whenever the add row button is clicked. I am creating the button programmatically and adding it to the table header. Below that button, and on the same column there will be delete row buttons too.
我虽然有一个问题,当我点击该按钮时,不会被调用的事件。我是不是正确的创建按钮?如果没有,那我怎么办呢?如果我的话,你知道是什么问题?
I am having a problem though, when I click the button, the event is not being called. Am I creating the button correctly? If not, then how do I do it? If I am, then do you know what the problem is?
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);
}
}
再一次,将出现按钮,但它并没有输入正确的事件方法。
感谢您的帮助和时间:)
Once again, the button appears, but it does not enter the correct event method. Thanks for your help and time :)
顺便说一句,当我做到这一点声明,例如:
By the way when I do it declaratively such as:
<asp:Button ID="BTNAdd" runat="server" Text="Add New Row" OnClick="AddNewRow_Click" />
该事件将注册并运行完全正常。
the event will register and work completely fine.
最新资讯:
我也出现过一个删除按钮,我没有用它注册任何类型的事件,但是当我点击它,它做同样的事情作为添加行按钮,可这是因为母版页或不同的源告诉按钮首先应该做什么或默认?
NEW INFO: I have a delete button appearing too, I did not register any type of event with it, but when I click it, it does the exact same thing as the add row button, could this be because the master page or a different source is telling the buttons what to do first or by default?
感谢:)
推荐答案
您应该添加动态控件在页面的Init事件处理程序,以便ViewState中和事件触发适当
You should add the dynamic controls in the Page's Init event handler so that the ViewState and Events are triggered appropriately.
试着这样做:
protected void Page_Init(object sender, EventArgs e)
{
Button btn = new Button();
btn.ID = "btnTest";
btn.Text = "I was dynamically created";
btn.Click += new EventHandler(btnTest_Click);
Panel1.Controls.Add(btn);
}
这篇关于ASP.NET编程添加按钮与事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!