繁体   English   中英

如何绑定WinForm的列表框selectedItems

[英]How to bind WinForm's listbox selecteditems

我有一个“所有选择”的列表框,以及一个对所有这些选择都为0的对象(因此具有多值选择模式的列表框)。 我需要选择在该列表框中选择的所有对象选择。

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

假设我们有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”,因为它是只读的

我不确定我是否正确,但如果我做到了,是的,您可以做到。

例如:

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

希望你从中得到逻辑。 由于您提供的代码为零,因此我再也无法为您提供帮助。 干杯!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM