簡體   English   中英

Codebehind中的ASP.NET下拉列表與ASPX頁面中的相關聯

[英]ASP.NET Dropdown List in Codebehind vs in ASPX page

我在代碼隱藏中生成一個下拉列表,無法自動觸發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>

問題可能在於您沒有及早將控件添加到頁面。 需要在頁面生命周期的早期添加控件以使其事件處於捆綁狀態。

您可能在Load事件中執行此操作,為時已晚。 嘗試在Init事件期間添加它或覆蓋CreateChildControls方法。

編輯:正如Dave Swersky所提到的,請確保在每個頁面請求(包括回發)上執行此操作。

你的代碼中有一個網格物體。 嘗試進行創建,數據綁定和事件調用。

例:

<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));
}

詳細說明Mike Mooney的答案:您還需要確保在每次回發時將控件添加回控件樹 在每個回發上重新創建控制樹,從標記讀入。 如果以編程方式再次添加它並且從不再添加它,則樹中無法控制接收事件。

我遇到的問題是,如果下拉列表沒有AutoPostBack = true,那么它永遠不會調用該函數。

您似乎沒有將控件添加到控件集合中。 您必須在控件層次結構中的某處添加控件,並確保在每次回發時添加該控件以確保存在接收事件的控件。 通過添加控件,您不需要直接調用RenderControl。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM