【发布时间】:2015-06-03 16:42:40
【问题描述】:
我的 ASP.NET Webforms 应用程序,我有一个 table,我在其中动态添加所有数据。一行在每个单元格中包含Buttons。我希望按钮在用户单击它时触发 onclick 事件。但是,使用下面的代码,事件永远不会触发并且表格消失。这是代码:
<asp:Table ID="floorTable" runat="server" Width="100%" GridLines="Both">
</asp:Table>
在代码后面
// This method is called on a DropDownList SelectedItemChanged Event - so
// the buttons cannot be created in Page_Load or so. Have to create
// totally based on the DropDown selected item.
private void PopulateFloorRow(int floorNo, FloorPattern fp)
{
int cols = fp.UnitPattern.Count;
// HEADER ROW
TableRow thead = new TableRow();
thead.Width = Unit.Percentage(100);
thead.TableSection = TableRowSection.TableHeader;
TableCell theadCell = new TableCell();
theadCell.ColumnSpan = cols;
Label title = new Label();
title.Text = "Floor # " + floorNo;
theadCell.Controls.Add(title);
thead.Controls.Add(theadCell);
TableRow planRow = GetFloorPlan(floorNo, fp);
TableRow tr = new TableRow();
TableCell tc = null;
int tcWidPerc = (int)fp.UnitPattern.Count / 100;
foreach (UnitPattern up in fp.UnitPattern)
{
tc = new TableCell();
Button imgBtn = new Button();
// On Adding BELOW Line - ERROR - 0x800a1391 - JavaScript runtime error: 'UnitLinkClicked' is undefined
//imgBtn.Attributes.Add("onClick", "UnitLinkClicked(this)");
imgBtn.CommandArgument = up.UnitPatternId.ToString(); // I want to know which button is pressed. So, sort of Tag
imgBtn.Click += new EventHandler(UnitLinkClicked);
imgBtn.BorderWidth = Unit.Pixel(10);
imgBtn.BorderColor = Color.Transparent;
imgBtn.Width = Unit.Percentage(100);
if (up.UnitNo != null)
{
imgBtn.Text = up.UnitNo;
}
tc.Controls.Add(imgBtn);
tr.Controls.Add(tc);
}
floorTable.Rows.Add(thead);
floorTable.Rows.Add(planRow);
floorTable.Rows.Add(tr);
// Create Footer
PopulateTableFooter(cols);
}
protected void UnitLinkClicked(object sender, EventArgs e)
{
Button btn = (Button)(sender);
string upId = btn.CommandArgument;
System.Diagnostics.Debug.WriteLine("LINK Button clicked Of UP ID :" + upId);
}
编辑:添加了 SELECTEDiINDEXCHANGED 的代码
我的 DropDown_SelectedIndexChanged 代码:
protected void floorDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
if (selectedProject == null)
selectedProject = _db.Projects.Find(projectsList.SelectedValue);
System.Diagnostics.Debug.WriteLine("SELCTED Project = " + selectedProject.ProjectId);
// "Select Floor" is selected, so Hide floor Table
if (floorDropDownList.SelectedValue == "-1")
{
floorTable.Visible = false;
}
else
{
int floorNo = int.Parse(floorDropDownList.SelectedValue);
if (floorNo > 0)
{
PopulateFloorRow(floorNo, (FloorPattern)selectedProject.FloorPattern.ElementAt(floorNo - 1));
}
}
}
如果我在下拉列表中选择了“3”,表格将按预期显示。我点击一个按钮,表格消失了,但下拉列表中的值仍然只有“3”。
编辑部分
使用上面的代码,当我点击一个按钮时,UnitLinkClicked 事件永远不会被触发(我添加了断点)并且整个表格消失了。
你能说这会是什么问题吗?默认情况下,按钮是 AutoPostBack 并且它也没有该属性。我在这里缺少什么以及如何解决这个问题。几天以来我一直坚持这一点并试图弄清楚。
非常感谢任何帮助。 谢谢
【问题讨论】:
-
为什么需要动态控件?
-
可能发布您的下拉更改事件代码。
标签: c# asp.net button dynamic onclick