我正在创建一个组件表,并且需要能够将下拉列表中的项添加到表中的每个项目。这些列表是使用类似这样的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)。Cell [0] .Controls [0];
答案 0 :(得分:2)
您应该能够使用以下内容访问表格行:
TableRow tblRow = (TableRow) button.NamingContainer;
然后使用FindControl选项访问DropDownList
DropDownList ddlMenu = (DropDownList) tblRow.FindControl("ddlRigActionTypeMenu");
然后显然是SelectedValue来捕获值