0

I am changing a code that was written in VB using .net framework 3.5. In here I have to bind some data from the database to a drop down list and then read the selected value. The code for binding data and reading data are as follows.

Public Sub setDropdown_test()
    Dim ds As New DataSet
    Dim dr As DataRow

    Try
        ds = Subject_Test.getSubjectDetails()

        dr = ds.Tables(0).NewRow()
        dr("SBJ_NAME") = "Select the subject"
        dr("SBJ_CODE") = "-1"
        ds.Tables(0).Rows.InsertAt(dr, 0)

        If ds.Tables(0).Rows.Count > 0 Then
            testDrop.DataTextField = ds.Tables(0).Columns("subject_name").Caption
            testDrop.DataValueField = ds.Tables(0).Columns("subject_code").Caption
            testDrop.DataSource = ds
            testDrop.DataBind()
        End If
    Catch ex As Exception
        'write an error here
    End Try
End Sub

Protected Sub testButton_Click(sender As Object, e As EventArgs) Handles testButton.Click
    PoupMessage("selected value is - " & testDrop.SelectedValue & " selected text is - " & testDrop.SelectedItem.ToString())
End Sub

in page Load method setDropdown_test() is called.

Data binding to drop down list is working properly. But every time I select a value and click the testButton the page reloads itself and gives the out put of first column of the drop down list. As far as I know, stop reloading the page is the best way to work this properly. but I failed to do that.
Can someone please help me to solve this.

1 Answer 1

1

It's resetting to the Dropdown's first item because of PostBack, which means in every click of your button, the form do a PostBack and reloads the form, calling the setDropdown_test() again, resetting the value to the first Item in the list.

Cover it with this statement to avoid reloading the DropDownList every PostBack.

If Not IsPostBack Then
     setDropdown_test()
End If
Sign up to request clarification or add additional context in comments.

1 Comment

Kindly mark this as answered by clicking the Check. :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.