开发者

.net DropDownList gets cleared after postback

开发者 https://www.devze.com 2023-01-06 15:52 出处:网络
This has been driving me nuts all day. I\'ve seen this problem crop up here a few times, essentially I have a drop down list that populates a fo开发者_StackOverflowrm below when it\'s changed - basic

This has been driving me nuts all day. I've seen this problem crop up here a few times, essentially I have a drop down list that populates a fo开发者_StackOverflowrm below when it's changed - basic stuff. On first page load everything is fine, but when the dropdownlist is changed, it's entirely blank after postback and the SelectedIndexChanged event never fires. I believe it all points to a viewstate problem. Here's the code..

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="EditUser.ascx.cs" Inherits="Controls_EditUser" %>
<asp:DropDownList OnSelectedIndexChanged="SelectedIndexChanged" AutoPostBack="true" ID="UsersList" EnableViewState="true"
    runat="server" DataTextField="EXTRANET_USER_EMAIL" DataValueField="EXTRANET_USER_ID">
</asp:DropDownList>

and the pageload...

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        IEnumerable<ExtranetUser> users = Users();
        UsersList.DataSource = users;
        UsersList.Items.Insert(0, new ListItem("-- Select User --", "0"));
        UsersList.DataBind();
    }
}

Any help on this would be hugely appreciated! I'm sure it's something simple...


Edit: Completely new answer...

Are you adding the control in the Page_Init event? Any later than this and the ViewState will have already been parsed and applied to the controls on the page, before the dynamically added control has been added. See this: http://msdn.microsoft.com/en-us/library/ms178472.aspx


Try adding the EnableViewState on the Page directives also

<%@ Control Language="C#" EnableViewState="True" AutoEventWireup="true" CodeFile="EditUser.ascx.cs" Inherits="Controls_EditUser" %>

Also, the ordering of the items on postback are important to preserve the ViewState. could it be, that after postback, some controls bevore that one are missing?

0

精彩评论

暂无评论...
验证码 换一张
取 消