简体   繁体   中英

Listbox with linq and multiple selection

Got 2 listboxes: Patients and Sessions. Need to display filtered (with linq query) info in the second one, based on multiple selection in the first one.

Commented string works but allows only one item to be selected in the first listbox.

I definitely know that it successfully gathers Patients to List variable but when I use Contains the second listbox is empty.

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    DataClasses1DataContext dbContext = new DataClasses1DataContext();
    List<string> selectedItems = (from object o in listBox1.SelectedItems select listBox1.GetItemText(o)).ToList();
    listBox2.DataSource = dbContext.Sessions
    //.Where(pID => pID.PatientID == listBox1.GetItemText(listBox1.SelectedValue))
      .Where(pID => selectedItems.Contains(pID.PatientID));
    listBox2.DisplayMember = "Start";
    listBox2.ValueMember = "SessionID";
}

Session and dbContext class definitions:

public partial class Session : INotifyPropertyChanging, INotifyPropertyChanged
    {
    ...
    public int SessionID
        {
        ...
        }
    public string PatientID
        {
        ...
        }
    }

public partial class DataClasses1DataContext : System.Data.Linq.DataContext
    {
    ...
    public System.Data.Linq.Table<Session> Sessions
        {
        ...
        }
    }

I dont know what type of element you are having in your listbox1. I assumed the type is named Session :

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        DataClasses1DataContext dbContext = new DataClasses1DataContext();
        List<string> selectedItems = (from object o in listBox1.SelectedItems select listBox1.GetItemText(o)).ToList();
        listBox2.DataSource = dbContext.Sessions
            .Where(pID => listBox1.SelectedItems.OfType<Session>().Select(x => x.PatientID).Contains(pID.PatientID));
        listBox2.DisplayMember = "Start";
        listBox2.ValueMember = "SessionID";
    }

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