【发布时间】:2014-03-08 08:51:39
【问题描述】:
我正在创建一个组件表,并且需要能够将下拉列表中的项目添加到表中的每个项目。这些列表是使用这样的 foreach 以编程方式添加的:
MyDatabase db = new MyDatabase();
if (db.ComponentTypes.Count() > 0)
{
foreach (ComponentType componentType in db.ComponentTypes)
{
// Header row components
TableRow componentRow = new TableRow();
TableCell componentTypeCell = new TableCell();
// Create Header Row
componentTypeCell.ColumnSpan = 5;
componentTypeCell.Text = componentType.Name;
componentTypeCell.Attributes.Add("style", "background: black; color: white; font-weight: bold;");
componentRow.Cells.Add(componentTypeCell);
tblRigActionTypesAndComponentTypes.Rows.Add(componentRow);
// Middle portion omitted for simplicity
//=================================================
// Relevant portion
// DDL Row Components
TableRow addActionRow = new TableRow();
TableCell rigActionTypeMenuCell = new TableCell();
TableCell addRigActionTypeButtonCell = new TableCell();
DropDownList ddlRigActionTypeMenu = new DropDownList();
Button addRigActionTypeButton = new Button();
// Populate dropdown with action types
Helper.PopulateDropdownWithActionTypes(ddlRigActionTypeMenu);
rigActionTypeMenuCell.Controls.Add(ddlRigActionTypeMenu);
addRigActionTypeButton.Text = "Add This Action";
addRigActionTypeButton.CommandName = "Add";
addRigActionTypeButton.CommandArgument = componentType.ID.ToString();
addRigActionTypeButtonCell.ColumnSpan = 4;
addRigActionTypeButtonCell.Controls.Add(addRigActionTypeButton);
addActionRow.Cells.Add(rigActionTypeMenuCell);
addActionRow.Cells.Add(addRigActionTypeButtonCell);
tblRigActionTypesAndComponentTypes.Rows.Add(addActionRow);
}
}
按钮处理程序
protected void ButtonHandler(object sender, EventArgs e)
{
Button button = (Button)sender;
MyDatabase db = new MyDatabase();
if (button.CommandName == "Add")
{
// How do I capture the selected value from the
// dropdown menu paired with the "add" button?
}
}
使用CommandArgument属性很容易捕获按钮所属的组件,但是如何获取对应的DDL呢?
更新:Moe S' 方法
我无法让它工作。我尝试了几种不同的方法来使用button.NamingContainer 访问下拉菜单,但一直遇到Object reference not set to an instance of an object. 错误。我的最后一次尝试如下:
Control control = button.NamingContainer;
Control test = control.FindControl("ddlRigActionTypeMenu");
lblPageHeader.Text = test.UniqueID;
更新 2:
为了进一步了解上述(非工作)代码,以下确实有效:
Control control = button.NamingContainer;
lblPageHeader.Text = button.NamingContainer.UniqueID;
这会将页眉更改为dnn$ctr498$AssignRigActionTypesToComponentTypes
已解决
我将 Moe 标记为已接受的答案,因为他让我指出了正确的方向,但 Parent 最终为我工作,而不是 NamingContainer。尽管如此,所有相同的原则仍然适用。
解决方法:
DropDownList ddl = (DropDownList)((TableRow)((TableCell)button.Parent).Parent).Cells[0].Controls[0];
【问题讨论】:
-
这是winforms、WPF、Web应用吗?
-
@BlackICE 不,不是。不过感谢您的回复!
-
那是个什么样的应用呢?
-
@BlackICE DotNetNuke 5.(不幸的是)