我正在創建組件表,並且需要能夠將項目從下拉列表添加到表中的每個項目。這些列表添加程序使用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?
更新:萌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不,它不是。儘管謝謝你的迴應! – drewwyatt
它是什麼樣的應用程序呢? – BlackICE