简体   繁体   中英

AutoPostBack=“true” doesn't work for DropDownList with DataSource

I have following *.aspx page

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Test.aspx.cs" Inherits="Admin_Test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form2" runat="server">
<div>
    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataTextField="Name" DataValueField="FieldKey" />

    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

</div>
</form>
</body>
</html>

and *.aspx.cs page

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Linq;

public partial class Admin_Test : System.Web.UI.Page 
{
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DataClassesDataContext datacontext = new DataClassesDataContext();
        DropDownList1.DataSource = datacontext.GetAllDepartments(false);
        DropDownList1.DataBind();
    }


}
}

When I change the value in dropdownList (in browser), it does PostBack, but it selects the first item of list after PostBack - it doesn't save my value.

GetAllDepartments(isDeleted) is a stored procedure, it returns a List of objects with two properties - FieldKey and Name.

You can set the event like this:

protected void Page_Load(object sender, EventArgs e)
{
    DropDownList1.SelectedIndexChanged += new System.EventHandler(this.On_SelectedIndexChanged);

    if (!IsPostBack)
    {
        DataClassesDataContext datacontext = new DataClassesDataContext();
        DropDownList1.DataSource = datacontext.GetAllDepartments(false);
        DropDownList1.DataBind();
    }


}

It seem to me that there is something wrong with the ViewState. Have you somehow disabled ViewState?

我找到了一个答案-* .dbml已过时,GetAllDepartments的每个FieldKey都返回0-因此,存在项的重复值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM