Link to home
Start Free TrialLog in
Avatar of jcorra
jcorra

asked on

Drop Down List contents (database-driven) disappear on Postback

I'm writing an ASP.NET web application where certain fields in the form are drop-down lists populated with values stored in a MS-SQL2000 database.  I can get the lists to display correctly when the page initially loads, but the list contents disappear on PostBack.  The drop-down lists themselves don't perform AutoPostBack, but there is also an ASP Calendar control on the same page, and whenever a new date is selected all the list contents disappear.  To test I also tried creating just a simple testpage with only a single drop-down list, which is set to AutoPostBack, and the same thing happens--as soon as an option in the list is selected, the list contents disappear.

I'm still fairly new to programming in .NET, but putting the drop-down initialization inside the "If Not Page.IsPostBack" statement is something I've seen in several online .NET tutorials, as it saves the overhead of the database call and avoids over-writing the selected value on PostBack.  But I haven't been able to find anything about how to make the drop-down lists persist, everything I've read makes it seem like the drop-down lists will just automatically persist if it's not overwritten on PostBack.

I thought maybe the problem was that I'm databinding my drop-down list to a dynamically created SqlCommand which is created inside an "If Not Page.IsPostBack" statement, so I tried making the SqlCommand and SqlConnection objects members of the web form itself, but the same thing still happens.  I've also tried it with EnableViewState set to both true and false.  Is something configured incorrectly on my server that's causing this problem?  Here's the source from my test page:

[BEGIN TestDropDown.aspx]

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="TestDropDown.aspx.vb" Inherits="Test.TestDropDown"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
     <HEAD>
          <title>TestDropDown</title>
          <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
          <meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1">
          <meta name="vs_defaultClientScript" content="JavaScript">
          <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
     </HEAD>
     <body>
          <form id="Form1" method="post" runat="server">
               <asp:DropDownList id="DropDownList1" runat="server" DataTextField="SeminarName" DataValueField="SeminarID"
                    AutoPostBack="True"></asp:DropDownList>
          </form>
     </body>
</HTML>
[END TestDropDown.aspx]



[BEGIN TestDropDown.aspx.vb]

Imports System.Data
Imports System.Data.SqlClient

Public Class TestDropDown
    Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents DropDownList1 As System.Web.UI.WebControls.DropDownList

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        If Not Page.IsPostBack Then
            Dim conn As New SqlConnection(ConfigurationSettings.AppSettings("ExtConnString"))
            Dim getData As New SqlCommand("SELECT * FROM Seminars_Master", conn)
            conn.Open()
            DropDownList1.DataSource = getData.ExecuteReader(CommandBehavior.CloseConnection)
            DropDownList1.DataBind()
        End If
    End Sub

End Class
[END TestDropDown.aspx.vb]
Avatar of jnhorst
jnhorst

You want EnableViewState set to true.  If view state is enabled, you should be able to make a selection on the dropdown, have that fire a postback, and still have you list data (which will have been retrieved from viewstate) as well as the selected item.  Same if you fire the postback from another control.  Check your EnableViewState in the drop down list control.  I tried a similar setup as yours and with EnableViewState=true, it kept the list and the selection.  With it set to false, the list disappeared after the postback.

John
Hi there,
Close your connection...
        If Not Page.IsPostBack Then
            Dim conn As New SqlConnection(ConfigurationSettings.AppSettings("ExtConnString"))
            Dim getData As New SqlCommand("SELECT * FROM Seminars_Master", conn)
            conn.Open()
            DropDownList1.DataSource = getData.ExecuteReader(CommandBehavior.CloseConnection)
            DropDownList1.DataBind()
            conn.Close()
        End If
-Baan
Avatar of jcorra

ASKER

As I mentioned in my original post, I had tried setting EnableViewState="true" for the control itself:
[quote] ...I've also tried it with EnableViewState set to both true and false. [/quote]

I just discovered, though, that ViewState can be set at other levels like in the web.config file.  Looks like it works if I add <pages enableViewState="true" /> inside my web.config file for this project, or change the top line of my .aspx page to say
<%@ Page ...[other stuff]... enableViewState="true">

(Baan- I am closing my connection:
DropDownList1.DataSource = getData.ExecuteReader(CommandBehavior.CloseConnection)
Giving "CommandBehavior.CloseConnection" as an argument when you call "SqlCommand.ExecuteReader()" automatically closes the connection when the SqlCommand finishes execution.)
ASKER CERTIFIED SOLUTION
Avatar of GhostMod
GhostMod
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial