【问题标题】:How to bind WinForm's listbox selecteditems如何绑定 WinForm 的列表框选定项
【发布时间】:2014-07-31 19:45:10
【问题描述】:

我有一个“所有选择”的列表框和一个对象,其中所有选择的选项都为 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”,因为它是只读的

【问题讨论】:

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


    【解决方案1】:

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

    例如:

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

    希望你能从中得到逻辑。既然你给了零代码,我就帮不了你了。干杯!

    【讨论】:

    • @Prokursors 你让它工作对了吗?我是在我的随机应用程序中这样做的。
    • 嗯,我按照您建议的方式进行了操作,但不知何故,我想也许有更简单的方法,例如使用对选定项目的绑定,诸如此类...
    • @Prokurors 我不这么认为,但你总是希望有人能发布一个简单的答案。有时候,做事没有简单的方法=P
    • 你的权利 :) 我只是在可能的情况下尽量保持代码更小 - 这就是为什么我会在可能的情况下尝试找到更简单的解决方案,但在这种情况下,我的选定项目似乎没有数据绑定的可能性猜测
    • 我的解决方案以某种方式给出了意想不到的结果(例如选择了比需要更多的项目),但您的似乎工作正常 - 所以我接受您的解决方案作为答案 - 感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2010-11-28
    • 1970-01-01
    • 2013-01-17
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    相关资源
    最近更新 更多