简体   繁体   English

为什么我的组合框项目没有被发现和选择?

[英]Why is my combobox item not being discovered and selected?

Inspired by the answer here , I refactored my code to add a record to my generic list after its initil population via LINQ, and then attempt to select that added item in the combobox that is assigned the contents of the list. 受到此处答案的启发,我重构了代码,以在通过LINQ初始化填充后将记录添加到我的通用列表中,然后尝试在分配了列表内容的组合框中选择添加的项目。

For some context/conceptualization, the combo box gets populated with candidate students; 对于某些上下文/概念化,组合框中填充了候选学生。 if the week being displayed has already been scheduled, though, the student already scheduled in that slot for that week is inserted into the list that serves as the combobox's DataSource after the others. 但是,如果已经计划了要显示的星期,则将已经在该时段安排的那个星期的学生插入到列表中,该列表将在其他星期之后用作组合框的数据源。 Finally, if such a student does exist in the combobox, my intent is to select that one (but the others remain available in the list in the event a change of assigned student needs to be made). 最后,如果组合框中确实存在这样的学生,我的目的是选择一个(但如果需要更改分配的学生,则其他人仍在列表中可用)。

Here is the code: 这是代码:

private void PopulateBibleReadingComboBox()
{
    int BIBLE_READING_TALK_TYPE = 1;
    if (!System.IO.File.Exists(AYttFMConstsAndUtils.STUDENTS_FILENAME)) return;
    if (null == studentsList) return;
    string assignedStudentFirstname = string.Empty;
    string assignedStudentLastname = string.Empty;
    Student assignedStudent = null;

    if (currentWeekSaved)
    {
        DateTime currentWeek = Convert.ToDateTime(comboBoxWeekToSchedule.SelectedValue);
        AssignmentHistory ah = AYttFMConstsAndUtils.AssignmentHistList
            .FirstOrDefault(i => i.WeekOfAssignment == currentWeek && i.TalkType == 1);
        assignedStudentFirstname = AYttFMConstsAndUtils.GetStudentFirstNameForID(ah.StudentID_FK);
        assignedStudentLastname = AYttFMConstsAndUtils.GetStudentLastNameForID(ah.StudentID_FK);
        assignedStudent = new Student() {FirstName = assignedStudentFirstname, LastName = assignedStudentLastname, StudentID = ah.StudentID_FK};
    }
    List<Student> BRStudents =
    studentsList.Where(h => h.EnrolledInAYttFM)
        .Where(i => i.RecommendedNextTalkTypeID.Equals(BIBLE_READING_TALK_TYPE))
        .OrderBy(j => j.WeekOfLastAssignment)
        .ToList();
    if (null != assignedStudent)
    {
        BRStudents.Add(assignedStudent);
    }
    comboBoxBR.DataSource = BRStudents;
    comboBoxBR.DisplayMember = "FullName";
    comboBoxBR.ValueMember = "StudentID";
    if (null != assignedStudent))
    {
        comboBoxBR.SelectedIndex = comboBoxBR.Items.IndexOf(assignedStudent.FullName);
    }
}

The problem is that although the conditional "SelectedIndex/IndexOf" line is reached, and assignedStudent.FullName is what it should be, and is now added to the list and then the combobox, that item is not selected with that line: 问题是,虽然条件“的SelectedIndex /的IndexOf” 达到行,assignedStudent.FullName是它应该是什么, 现在添加到列表中,然后组合框,该项目与该行选择:

comboBoxBR.SelectedIndex = comboBoxBR.Items.IndexOf(assignedStudent.FullName);

Rather, comboBoxBR.SelectedIndex is -1 (although, again, that fullName does exist in the combobox at that point). 而是,comboBoxBR.SelectedIndex为-1(尽管再次说明,此时fullName确实存在于组合框中)。

Note: The "FullName" member of the Student class is calculated: 注意:Student类的“全名”成员的计算如下:

public class Student
{
    public int StudentID { get; set; }
    . . .
    public string FirstName { get; set; }
    public string LastName { get; set; }
    . . .
    public string FullName
    {
        get
        {
            return string.Format("{0} {1}", FirstName, LastName);
        }
        set { ; } 
    }
}

The list is made up of Student objects, but FullName is a string. 该列表由Student对象组成,但是FullName是一个字符串。 You need to look for the entire Student object. 您需要查找整个Student对象。 You'll want to change the line in question to: 您需要将相关行更改为:

comboBoxBR.SelectedIndex = comboBoxBR.Items.IndexOf(assignedStudent);

When you use a DataSource it is as if the objects have been added to the collection (and in some form or fashion that may well be the case under the hood). 当您使用DataSource ,就好像已将对象添加到集合中(并且可能以某种形式或方式在幕后)一样。 So, searching for just the name in the items collection will fail. 因此,仅在item集合中搜索名称将失败。 A more MCVE: 更多MCVE:

Students = new List<Student>();

Students.Add(new Student(7, "Zowie", "Halston"));
Students.Add(new Student(6, "Ziggy", "Watson"));
Students.Add(new Student(18, "Zalgo", "d'Artagnan"));
Students.Add(new Student(67, "Tabitha", "Black"));

Student luckyStudent = Students.First(w => w.FirstName == "Ziggy");

cbo1.DataSource = Students;
cbo1.DisplayMember = "FullName";
cbo1.ValueMember = "Id";

Then, setting the selection: 然后,设置选择:

if (luckyStudent != null)
{ 
    // set selected: (WORKS):
    //cbo1.SelectedItem = luckyStudent;

    // set Index of item (WORKS):
    //cbo1.SelectedIndex = cbo1.Items.IndexOf(luckyStudent);

    // set Index of item name (FAILS):
    cbo1.SelectedIndex = cbo1.Items.IndexOf(luckyStudent.FullName);
}   

Generally, when using a DataSource , I try to avoid fiddling with the items collection at all. 通常,在使用DataSource ,我会尽量避免摆弄项目集合。 If you try to add or remove from items you get yelled at. 如果尝试在items添加或删除items您会大吼大叫。 So, for this, I would use 因此,为此,我将使用

cbo1.SelectedItem = luckyStudent;

You can find them in the collection, but it can help you lose track that the control is bound. 您可以在集合中找到它们,但是它可以帮助您失去对控件绑定的跟踪。

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

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