简体   繁体   中英

populate listbox from sql db where 3 fields meet textbox values

I am trying to return rows in a listbox from a sql database. I only want the rows to be returned where 3 fields match textbox values. Currently, the listbox is returning ALL rows if ANYTHING is typed into any of the 3 textboxes. If nothing is typed in , nothing shows up (that part is the expected/correct behavior). My code is:

  Private Sub tireselect_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    m_cn.ConnectionString = "Data Source=localhost;Initial Catalog=tires;Integrated Security=True"
    m_cn.Open()
    'Dim con As New SqlConnection()
    'Dim cmd As String = "Select brand, model, width, aspect, rim, retail from dbo.tires"
    Dim sqltext = "SELECT [ID] ,[brand] ,[model] ,[cost] ,[retail] ,[width] ,[aspect] ,[rim] FROM [tires].[dbo].[tires]"
    Using sqlCon = New SqlConnection("Data Source=localhost;Initial Catalog=tires;Integrated Security=True")
        sqlCon.Open()


        Dim cmd = New SqlCommand(sqltext, sqlCon)
        cmd.Parameters.AddWithValue("@tirewidth", (Int(TireLookup.txtWidth.Text)))
        cmd.Parameters.AddWithValue("@tireaspect", (Int(TireLookup.txtAspect.Text)))
        cmd.Parameters.AddWithValue("@tirerim", (Int(TireLookup.txtRim.Text)))
        cmd.ExecuteNonQuery()
    End Using

    Dim m_da As New SqlDataAdapter("SELECT [ID] ,[brand] ,[model] ,[cost] ,[retail] ,[width] ,[aspect] ,[rim] FROM [tires].[dbo].[tires] where [width]=tirelookup.txtwidth.text AND [aspect]=tirelookup.txtwidth.text AND [rim]=tirelookup.txtrim.text", m_cn)
    Dim myDataSet As New DataSet()
    m_da.Fill(myDataSet, "dbo.tires")
    Dim myDataTable As DataTable = myDataSet.Tables(0)
    Dim tempRow As DataRow
    For Each tempRow In myDataTable.Rows
        ListBox1.Items.Add(tempRow("brand"))
        ListBox2.Items.Add(tempRow("model"))
        ListBox3.Items.Add(tempRow("width") & " / " & tempRow("aspect") & " / " & tempRow("rim"))
        ListBox4.Items.Add("$ " & tempRow("retail") & "   Tire ID=" & (tempRow("ID") - 1))
    Next
End Sub

You need to change your predicates like this:

  where [width]=@tirewidth 
  AND [aspect]=@tireaspect
  AND [rim]=@tirerim

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM