如何绑定WinForm's列表框的选定项

本文关键字:列表 何绑定 绑定 WinForm | 更新日期: 2023-09-27 18:08:06

我有一个列表框的"所有的选择"和一个对象,有0到所有这些选择选择(所以listbox与多值选择模式)。我需要选择列表框中所有对象的选项

所以我绑定了ListBox。Datasource到所有可用选项的列表,并试图找到一种方法将该对象的选择绑定到Listbox SelectedItems属性,但我没有找到任何关于如何做到这一点的信息。

假设我们有3个表:Students, Courses和studentcourses。因此,在Student的表单中,我需要有一个列表框,其中包含所有可用的课程,并在该列表中选择他的studentcourses表中的所有学生课程。

是可能得到这个使用数据绑定?

我尝试的方式

//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");

但是当我尝试这样做时,我得到一个错误:不能绑定到属性'SelectedItems',因为它是只读的

如何绑定WinForm's列表框的选定项

我不确定我是否理解对了,但如果我理解对了,是的,你可以做到。

例如

:

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);
    }
}

希望你明白了这里的逻辑。既然你没有给出代码,我也帮不了你。干杯!