Solved

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

Posted on 2004-09-12
4
875 Views
Last Modified: 2012-06-21
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]
0
Comment
Question by:jcorra
4 Comments
 
LVL 10

Expert Comment

by:jnhorst
ID: 12041416
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
0
 
LVL 18

Expert Comment

by:DotNetLover_Baan
ID: 12043712
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
0
 
LVL 1

Author Comment

by:jcorra
ID: 12046768
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.)
0
 
LVL 1

Accepted Solution

by:
GhostMod earned 0 total points
ID: 12048345
PAQd, 125 points refunded - asker posted solution

GhostMod
Community Support Moderator
0

Featured Post

ScreenConnect 6.0 Free Trial

Check out the updates in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI that improves session organization and overall user experience. See the enhancements for yourself!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on www.johnchapman.name could not pull conte…
In an ASP.NET application, I faced some technical problems. In this article, I list them out and show the solutions that I found.  I hope it will be useful. Problem: After closing a pop-up window, the parent page should be refreshed automaticall…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

821 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question