Method to prevent drop-down list from duplicating items in ASP.NET VB.NET
P粉299174094
P粉299174094 2023-09-07 09:26:11
0
1
557

Public Sub Table()      
    Dim Connection As MySqlConnection

    Dim DataAdapter As MySqlDataAdapter
    Dim Command As MySqlCommand
    Connection = New MySqlConnection("server=localhost; userid=root; database=setting;")
    Command = New MySqlCommand("Select * FROM table", 
    Connection)
    DataAdapter = New MySqlDataAdapter(Command)
    Dim DataTable As New DataSet
    DataAdapter.Fill(DataTable)
    Ddlname.DataSource = DataTable
    Ddlname.DataTextField = "Name"
    Ddlname.DataValueField = "Name"
    Ddlname.DataBind()
End Sub

P粉299174094
P粉299174094

reply all(1)
P粉883973481

You are not showing your markup, but remember that any button click, control with automatic postback, or any event firing on the page will re-run the page load event.

So, in theory, even a simple button click might rerun the code that loads the combo box. So every event, every click may add or load the combobox again.

Therefore, the design pattern of almost every page is to load grids, list boxes, drop-down boxes, etc. only once.

So your code should look like this:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then
        LoadTable()
    End If
End Sub


Public Sub LoadTable()

    Using Connection As New MySqlConnection("server=localhost; userid=root; database=setting;")

        Using Command As New MySqlCommand("SELECT * from table", Connection)
            Connection.Open
            Dim MyTable As New DataTable
            MyTable.Load(Command.ExecuteReader)
            Ddlname.DataSource = DataTable
            Ddlname.DataTextField = "Name"
            Ddlname.DataValueField = "Name"
            Ddlname.DataBind()
        End Using
    End Using

End Sub

So make sure your page loading code has the very important If Not IsPostBack so that you can actually only load the code that loads the combobox once.

So this "is a postback" test? 99% of your pages will work this way. I often think that asp.net pages should have a "firstLoad" event because it fires every time the page loads, and this is true for any buttons and any code that triggers page postbacks. Therefore, your combobox will load (and grow) again and again because you run the code that loads the grid, listbox, or dropdown every time you load the page. So adopt, use and "like" the IsPostBack test - you do it for all your pages, and 99% or more of them require this test.

In fact, if you don't apply the above suggestions, you will almost never be able to build any functional web page.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template