【发布时间】:2011-02-24 12:03:42
【问题描述】:
ASP.Net 网络表单,.NET 2.0
我有一个难题。我有一个带有自定义控件的 aspx 页面:
<def:CustomControl ID="customID" runat="server" />
如果满足特定条件,自定义控件可以多次添加到 ASPX 页面:
<asp:Repeater runat="server" ID="options" OnItemDataBound="options_OnItemDataBound">
<HeaderTemplate>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
</HeaderTemplate>
<ItemTemplate>
<td>
<span>
<asp:Label runat="server" ID="optionName">
</asp:Label>
<asp:DropDownList runat="server" ID="optionValues" CssClass="PartOption" >
</asp:DropDownList>
</span>
</td>
</ItemTemplate>
<FooterTemplate>
</tr>
</table>
</FooterTemplate>
</asp:Repeater>
在 aspx 页面后面的代码中,我想将一个事件 (OnSelectedItemChange) 附加到实际上不在 ASPX 页面上的下拉控件(还)。但是,当我尝试在后面的代码中执行以下操作时:
foreach(Control eachControl in customID.Controls) {
if (eachControl.HasControls) {
Control DdControl = eachControl.FindControl("optionValues"); //always null
if (DdControl != null && DdControl is typeOf(DropDownList)) {
DdControl = DdControl as DropDownlist; //I might have the syntax wrong
//here, but you get the point.
//add event to control.
}
}
}
但是eachControl的所有东西都是一个repeater,它显示它的childcontrol计数为0。所以当它到达FindControl方法时,它总是返回null。
问题 所以我想要做的是将一个事件(OnSelectedItemChange)添加到转发器内的下拉列表控件(这是一个自定义控件,如果满足条件,则会添加到页面中)。在下拉列表中进行选择时,我希望它触发 Event 方法。
我该怎么做:
A) 如果页面上存在下拉列表控件,是否找到添加事件的方法?
或
B) 一种能够在后面的代码中调用方法并传递所有下拉列表中的选择的方法(因为可以多次添加自定义控件来创建多个下拉列表?
注意我面前没有代码,所以如果我有语法错误,请忽略。我也知道 ID 是唯一的,所以这也被认为是我的逻辑问题。当它呈现这些时,ID 可能会被 asp 名称约定破坏,我认为我必须找到一种解决方法。
【问题讨论】:
-
首先你尝试用什么方法来执行上面的代码?其次,为什么不在自定义控件上创建一个事件。这可能不是唯一一次有人想要订阅 selectionchanged 事件
-
你是说DropDownList的
SelectedIndexChanged事件吗? -
@LordCover - 是的。 @Rune FS - 我不确定我是否遵循。我更新了上面的自定义控件。但是由于自定义控件的代码是在单独的页面上,所以放在ASPX页面上的“
控件上会影响到自定义控件Repeater中嵌入的下拉列表控件吗?