简体   繁体   中英

How to display a select option based on SQL result - VB.net

I have some sample data here... Sample Data to query

The SQL is as follows;

 "Select Person, Travel, WithWho FROM database
       where (Person like '" & txtSearch.Text & "' 
       or Travel like '" & txtSearch.Text & "'
       or WithWho like '" & txtSearch.Text & "')"

I am displaying the ways of travel in a listbox which is populating fine. I am displaying the WithWho field in a textbox and this is where the problem is. It is populating the textbox with SARAH who is the first record in the database and ignoring JOANNE . This is in a WPF application. I was wondering does anyone know how I could provide an option to select which record to load or even to search through the records on the form.

Thanks for any help

Sample code to display WithWho in textbox

The code you posted will only display one name in the TextBox because it resets the entire value of the Text property, rather than concatenating additional names. You can fix this with the following:

txtPname.Text = ""
While reader.Read()
    countvalues += 1
    If reader("WithWho") Is DBNull.Value Then
        txtPname.Text &= Environment.NewLine & "Unknown"
    Else
        txtPname.Text &= Environment.NewLine & reader("WithWho")
    End If
End While

These results still won't be exactly what I think you want, but it's a start if you're set on the TextBox route. From your comments, however, I believe what you really want is a ListBox, populated like so:

lstPname.Items.Clear()
While reader.Read()
    Dim pName As String
    If reader("WithWho") Is DBNull.Value Then
        pName = "Unknown"
    Else
        pName = reader("WithWho")
    End If
    If Not lstPname.Items.Contains(pName) Then
        lstPname.Items.Add(pName)
    End If
End While

This will give the user a box where each name (including "Unknown", if applicable) will appear exactly once. Unlike a TextBox, they can then click the name and its row will immediately be highlighted. You can then code your other controls to respond to the lstPname.SelectedIndexChanged event to ascertain which person is selected and display the appropriate information.

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