简体   繁体   中英

How to bind WinForm's listbox selecteditems

I have a listbox of "all the choices" and an object that has 0 to all of those choices selected (so listbox with multivalue selectionmode). And I need to select all the object's choices selected in that listbox.

So I binded the ListBox.Datasource to the list of all available choices and tried to find a way to bind that object choices to the Listbox SelectedItems property, but I had no success on finding any information on how to do that.

EXAMPLE

let's say we have 3 tables: Students, Courses and StudentsCourses. So in the Student's form I would need to have a listbox with all the available Courses and in that list selected all the Students courses that is in his StudentsCourses table.

Is it possible to get this using databinding?

THE WAY I TRIED IT

//1. getting the available list
    List.DataSource = ..the list of all the courses
    List.DisplayMember = "Name";
    List.ValueMember = "Id";

//2. selecting the appropriate items in the list
    List.SelectedItems.Clear();                    
    foreach (var c in student.StudentsCourses)
    {
        //in this strange case Id is equal to the index in the list...
        List.SetSelected(c.CourseId, true);
    }

//instead of this "2." part I was hoping to use something like this:
    List.DataBindings.Add("SelectedItems", student.StudentsCourses, "CourseId");

but when I try to do that I get an error: Cannot bind to property 'SelectedItems' because it is read-only

I'm not sure if I got you right, but if I did, yes, you can do it.

For example:

List<KeyValuePair<string, Course>> coursesList = new List<KeyValuePair<string, Course>>();
List<Course> cList = // Get your list of courses

foreach (Course crs in cList)
{
    KeyValuePair<string, Course> kvp = new KeyValuePair<string, Course>(crs.Name, crs);
    cList.Add(kvp);
}

// Set display member and value member for your listbox as well as your datasource
listBox1.DataSource = coursesList;
listBox1.DisplayMember = "Key"; // First value of pair as display member
listBox1.ValueMember = "Value"; // Second value of pair as value behind the display member

var studentsList = // Get your list of students somehow

foreach (Student student in studentsList)
{
    foreach (KeyValuePair<string, Course> item in listBox1.Items)
    {
        // If students course is value member in listBox, add it to selected items
        if (student.Course == item.Value)
            listBox1.SelectedItems.Add(item);
    }
}

Hopefully you got the logic out of this. Since you gave zero code, I can't help you any better. Cheers!

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