Solved

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

Posted on 2004-09-12
4
873 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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

This article discusses the ASP.NET AJAX ModalPopupExtender control. In this article we will show how to use the ModalPopupExtender control, how to display/show/call the ASP.NET AJAX ModalPopupExtender control from javascript, how to show/display/cal…
I recently went through the process of creating a Calendar Control of events with the basis of using a database to keep track of the dates that are selectable, one requirement was to have the selected date pop-up in a simple lightbox.  At first this…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

744 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now