0

I have three database tables:

  • a list of cars,
  • a list of people, and
  • the third is the many-to-many table of people to cars.

On my winform for a person, I have a listbox of available cars. Loading that listbox from the database is easy (databinding). Is there any easy way to select what cars a person has based on the many to many table or do I have to resort to looping through the listbox and comparing it to the many to many table?

So, if I have John Doe and he owns a Ford and a Honda, and the choices in the lsitbox are Chevy, Honda, Ford, Toyota and Nissan, then only the Honda and Ford should be selected when John Doe's form is opened.

Thanks for the help!

David
  • 15,894
  • 22
  • 55
  • 66
  • Add `sql query` and `listbox binding code` to your question. – Veer May 20 '13 at 04:54
  • I'm asking for the code, how can I post it? – user2400461 May 22 '13 at 17:37
  • edit your question, add your code to it using `question help editor` to get right formatting – Veer May 22 '13 at 17:47
  • I'm not asking how to post code. In my question I'm asking for the code, there is nothing to post. I don't have the code, if I had the code, I wouldn't need this forum. Thank you. I figured it out anyhow doing this: for (int i = 0; i < ds2.Tables[1].Rows.Count; i++) { lstCars.SelectedIndex = Convert.ToInt32(ds2.Tables[1].Rows[i][0].ToString()); } – user2400461 May 23 '13 at 05:36

1 Answers1

0

Edit according to author's comment:

Alright I got that wrong at first. I guess there is no real "best practice", you will have to loop through the listbox either way.

Something like:

// Assuming dtPersonsCars is the DataTable containing two primary keys, persons and cars
       lstBoxCars.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple;
       for (int i = 0; i < lstBoxCars.Items.Count; i++)
       {
          if (dtPersonsCars.Rows.Find(new object[]{"PERSON", lstBoxAenderungen.Items[i].ToString()}) != null)
              lstBoxCars.SetSelected(i, true);
       }
ray
  • 149
  • 1
  • 4
  • 18
  • I don't think my explanation was written well. The listbox should contain all cars available to choose from. I want to know how to highlight or select the cars in the listbox that are associated with the user in the many to many table. I know how to get the data from the database and I know how to bind the datatable to the listbox, but what is the best solution to select the listbox items based on the many to many table? – user2400461 May 22 '13 at 02:07
  • Alright I got that wrong ;). See my edited answer. – ray May 22 '13 at 13:28