如何绑定WinForm的列表框选择项

时间:2014-06-10 21:37:58

标签: c# winforms data-binding listbox multi-select

我有一个“所有选项”的列表框和一个对所有选择的所有选项都有0的对象(所以带有多值选择模式的列表框)。我需要选择在该列表框中选择的所有对象选项。

因此,我将ListBox.Datasource绑定到所有可用选项的列表,并尝试找到将该对象选项绑定到Listbox SelectedItems属性的方法,但是我没有成功找到有关如何执行此操作的任何信息。 / p>

实施例

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

是否可以使用数据绑定获取此信息?

我试过的方式

//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',因为它是只读的

1 个答案:

答案 0 :(得分:3)

我不确定我是否帮助你,但如果我这样做,是的,你可以做到。

例如:

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

希望你有这个逻辑。由于您提供的代码为零,我无法为您提供更好的帮助。干杯!

相关问题