Ran
Ran

Reputation: 25

dropdownlist is cleared on page postback

I have a FormView bound to a SqlDataSource on my page. One of the controls on the FormView is a DropDownList, which gets populated on Page_Load (it's being populated with a list of file names from a specific folder).

Everything goes well when the page first loads. I am able to view the list of files, select one and, upon hitting the "save" button, store the correct filename in the database. However, when the page refreshes after the post back - the DropDownList is empty.

Code Behind for the page_load event:

If Not Page.IsPostBack Then  
  loadImageList()  
  End If  

The sub being called:

Protected Sub loadImageList()  
        Dim SaveLocation As String = Server.MapPath("/images/)  
        Dim di As New IO.DirectoryInfo(SaveLocation)  
        Dim fls As IO.FileInfo() = di.GetFiles()  
        Dim fi As IO.FileInfo  
        Dim drl As DropDownList = FormView1.FindControl("DropDownList_files")  
        drl.Items.Clear()  
        For Each fi In fls  
            drl.Items.Add(fi.Name.ToString)  
        Next  
    End Sub 

I have read a few post saying that this should do in the page_init event - but doing so results in an error.

Thank you in advance

Upvotes: 2

Views: 712

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460118

You should handle FormView's DataBound event and fill your DropDownList there:

    Private Sub FormView1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles FormView1.DataBound
        Select Case FormView1.CurrentMode
           Case FormViewMode.ReadOnly

           Case FormViewMode.Edit
              Dim DdlFiles= DirectCast(FormView1.FindControl("DropDownList_files"), DropDownList)
              Dim SaveLocation As String = Server.MapPath("/images/)  
              Dim di As New IO.DirectoryInfo(SaveLocation)  
              Dim fls As IO.FileInfo() = di.GetFiles()  
              Dim fi As IO.FileInfo  
              DdlFiles.Items.Clear()  
              For Each fi In fls  
                 DdlFiles.Items.Add(fi.Name.ToString)  
              Next  

              Case FormViewMode.Insert

         End Select
    End Sub

Maybe it will be cleared when the FormView is databound after postback.

Upvotes: 2

Related Questions