4

我在代码隐藏中生成一个下拉列表,无法让 selectedindexchanged 事件自动触发。直接放入 ASPX 页面时它工作正常,但我需要它在代码隐藏中。

这不起作用:

var deptList = new DropDownList
    {
        ID = "deptList",
        DataSource = departments,
        DataTextField = "deptname",
        DataValueField = "deptid",
        AutoPostBack = true,
        EnableViewState = true
    };

deptList.SelectedIndexChanged += new EventHandler(deptList_SelectedIndexChanged);
deptList.DataSource = departments;
deptList.DataTextField = "deptname";
deptList.DataValueField = "deptid";

if (!IsPostBack)
    deptList.DataBind();

deptList.Items.Insert(0, new ListItem("---Select Department---", string.Empty));

writer.Write("Select a department: ");
deptList.RenderControl(writer);

但这有效:

<asp:DropDownList ID="deptList" AutoPostBack="true" runat="server" OnSelectedIndexChanged="deptList_SelectedIndexChanged"></asp:DropDownList>
4

5 回答 5

7

问题可能在于您没有足够早地将控件添加到页面。需要在页面生命周期的早期添加控件以使其事件相关联。

您可能在 Load 事件中执行此操作,但为时已晚。尝试在 Init 事件期间添加它或覆盖 CreateChildControls 方法。

编辑:正如 Dave Swersky 提到的,确保在每个页面请求(包括回发)上都执行此操作。

于 2010-02-17T15:21:07.763 回答
2

详细说明 Mike Mooney 的回答:您还需要确保在每次回发时将控件添加回控件树中。 每次回发时都会重新创建控制树,并从标记中读取。如果您以编程方式添加一次且不再添​​加,则树中没有控件来接收事件。

于 2010-02-17T15:22:57.733 回答
2

您的代码中有一个网格。尝试划分创建、数据绑定和事件调用。

例子:

<asp:DropDownList ID="deptList" AutoPostBack="true" runat="server"></asp:DropDownList>

然后在后面的代码中(Page_Load):

deptList.SelectedIndexChanged += new EventHandler(deptList_SelectedIndexChanged);

if (!IsPostBack)
{
     deptList.DataTextField = "deptname";
     deptList.DataValueField = "deptid";
     deptList.DataSource = departments;
     deptList.DataBind();
     deptList.Items.Insert(0, new ListItem("---Select Department---", string.Empty));
}
于 2010-02-17T15:21:25.900 回答
0

我遇到的问题是,如果下拉列表没有 AutoPostBack = true 那么它永远不会调用该函数。

于 2012-11-13T10:38:06.753 回答
0

您似乎没有将控件添加到控件集合中。您必须在控件层次结构中的某处添加控件,并确保在每次回发时添加它,以确保控件存在以接收事件。通过添加控件,您不需要直接调用 RenderControl。

于 2010-02-17T15:33:42.007 回答