LINQ to SQL Search Query results to listbox, help transferring selecteditems to a new listbox

时间:2016-04-15 15:02:36

标签: sql vb.net linq listbox selecteditem

Hello and thank you for your help ahead of time!

I am doing a project with vb.net that involves searching a database table named 'Movies'. I have a related table 'Directors', and the goal of the project is to enable users to search and select movies to purchase.

I have figured out how to query the database using LINQ to SQL, and the results populate in my ListBox properly, but when I go to add the user's SELECTED ITEMS to a new listbox, or even try to display them in a messagebox, the result is not correct.

To be clear, the I am using LINQ to SQL because it allows me to manipulate related tables a lot easier and is much easier for querying than using plain SQL in vb.net.

Below is an example of my code

    Dim db As DataClasses1DataContext = New DataClasses1DataContext

    Dim searchstring As String = txtSearchbyText.Text
    Dim data As System.Linq.IQueryable(Of Project_2010Version.Movies)



    data = From m In db.Movies _
           Where m.MovTitle = searchstring _
           Select m

    ListBox1.DataSource = data.ToList
    ListBox1.DisplayMember = "MovTitle"
    ListBox1.ValueMember = "MovTitle"

What I want to do from here is allow users to select items from the listbox and then populate those items on a new "Order Form"

The problem I am running into is that the selected items being transferred do not display the correct values when trying to access them.

If I run the following code

Dim oitem As Object = Nothing

    For Each oitem In ListBox1.SelectedItems
        MsgBox(oitem.ToString())
    Next

My problem is the only thing I get in return is "Project2010Verion.Movies" instead of the movie's title.

How can I get the correct title so it can be displayed on a new form?

Thank you for your help!

2 个答案:

答案 0 :(得分:0)

Your problem with the iterator loop (For Each) is that you are calling ToString on an object, which, of course, will return the fully qualified name of the object in the list.

Look up what you have in the Movies class, pretty sure you want to structure it as:

For Each oitem In ListBox1.SelectedItems
        MsgBox(oitem.MovTitle)
    Next

答案 1 :(得分:0)

也许你应该尝试这样的事情......

对于ListBox1.SelectedItems中的每个oitem         MSGBOX(Listbox1.GetItemText(OITEM))     下一步