'how to prevent duplicate in dropdownlist asp.net vb.net. everytime i click the dropdownlist it duplicate the items

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


Solution 1:[1]

You don't show your markup, but remember, any button click, any control with autopost back, or any event trigger on the page will re-run the page load event.

So, in theory, even just a plane jane button click might well re-run your code that loads up the combo box. So each event, each click can potenail add or load up the combo box again and again.

So, the design pattern for near EVERY page is to only load the grids, the listbox, dropdowns (combo box) etc. is ONE time.

So, your code would and 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 load code has that all important If Not IsPostBack, so you REALLY only load + run your code to load the combo box one time.

So this "is Post back" test? 99% of all your pages will work this. I often thought that asp.net pages should have a "firstLoad" event, since page load WILL and DOES fire each and every time - and does so for ANY button, and ANY code that triggers a page post back. Hence, your combo box will load over and over (and grow and grow), since your running the code to load up the grid, the listbox, or dropdown list each time the page loads. So, adopt, use and "love" the IsPostBack test - you do this for all pages, and 99% if not more of my pages require that test.

In fact, you can't quite much build any functional web page if you fail to adopt the above advice.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Albert D. Kallal