Kenny
Kenny

Reputation: 1054

Why is the code duplicating search results?

The code below is supposed to allow the user to either search with specific record or perform a keyword search.

In other words, if the user just hits the search button, data is rendered to the screen.

The problem is that if you keep hitting the search button, the same record or records keep duplicating.

Any ideas?

Please see code and many thanks for your assistance.

Protected Sub bnt_Click(ByVal sender As Object, ByVal e As EventArgs) Handles bnt.Click

    Dim txtSearch As String

    'OR Perhaps pamametized query will be better
    txtSearch = searchBox.Text.Trim()

    Dim strSQL As String = ("SELECT fieldname FROM mytable WHERE keycode like '%' + @txtSearch + '%'")
    Dim connStr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim conn As New SqlConnection(connStr)
    Dim cmd As New SqlCommand(strSQL, conn)
    Dim objReader As SqlDataReader
    cmd.Parameters.AddWithValue("@txtSearch", strSearch)
    conn.Open()
    objReader = cmd.ExecuteReader()

    DataBind()

    While objReader.Read()
        With objReader
            Dim li As New ListItem(objReader(0).ToString())
            url.Items.Add(li)
        End With
    End While

    conn.Close()

End Sub

Upvotes: 0

Views: 73

Answers (2)

HatSoft
HatSoft

Reputation: 11201

You need to clear the old ones before you add new in the While loop

so just before the while loop you could url.Items.clear();

Upvotes: 1

Steven Doggart
Steven Doggart

Reputation: 43743

Try clearing the CheckBoxList control before adding the items:

url.Items.Clear()
While objReader.Read()
    With objReader
        Dim li As New ListItem(objReader(0).ToString())
        url.Items.Add(li)
    End With
End While

Upvotes: 1

Related Questions