因为很难说出我正在尝试做的事情,所以在解决这个问题时遇到了麻烦,但在这个例子中,我有三个从数据库中获取的数据表 . “人员”表,“组”表和“peopleInGroups”链接表 .

我有两个listView,一个用于显示特定组中人员的姓名,另一个用于显示不在该组中的人员 . 使用datarelation我可以从groupID获取组中人员的记录作为datarow []并使用简单的foreach循环填充“group in group”listView,但是我很难找到填充“people”的方法不在组“listView .

我最终得到的解决方案是创建两个新的数据表,一个用于“在组中”,一个用于“不在组中”,并在适当时填充/删除它们 . 这个过程看起来很混乱,但有点慢,我相信必须有更好的方法来达到同样的目的 .

方法中的代码(编辑了一下,尝试使其更通用):

private void PopulateListBoxes(string comboBoxGroupName)
    {
        // create copies of the "people" DataTable, one empty one full
        DataTable dtPeopleNotInGroup = myDataSet.Tables["people"].Copy();
        DataTable dtPeopleInGroup = myDataSet.Tables["people"].Clone();
        DataView dvPeopleNotInGroup = new DataView(dtPeopleNotInGroup, "", "PersonID", DataViewRowState.CurrentRows);
        DataView dvPeopleInGroup = new DataView(dtPeopleInGroup);

        // find the specific group row from the groups table using a specific groupID
        string stm = "groupid = somegroupid"
        DataRow[] drGroupID = dsMainDB.Tables["groups"].Select(stm);

        foreach (DataRow groupIDRow in drGroupID)
        {
            foreach (DataRow peopleInGroupRow in groupIDRow.GetParentRows(myDataSet.Relations["relPersonID"]))
            {
                // delete this row from the full datatable
                int removeThisPerson = dvPeopleNotInGroup.Find(peopleInGroupRow["PersonID"]);
                dvPeopleNotInGroup.Delete(removeThisPerson);

                // add this row to the empty data table
                dtPeopleInGroup.ImportRow(peopleInGroupRow);
            }
        }

        dvPeopleNotInGroup.Sort = "lastname";
        dvPeopleInGroup.Sort = "lastname";

        // populate the "In group" listView from the data view
        foreach (DataRowView inGroupRowView in dvPeopleInGroup)
        {
            listViewPeopleInGroup.Items.Add(new ListViewItem(new string[] { inGroupRowView["PersonID"].ToString(),
               inGroupRowView["FirstName"].ToString() + " " + inGroupRowView["LastName"].ToString() }));
        }

        // populate the "Not in group" listView from the data view
        foreach (DataRowView notInGroupRowView in dvPeopleNotInGroup)
        {
            listViewPeopleNotInGroup.Items.Add(new ListViewItem(new string[] { notInGroupRowView["PersonID"].ToString(),
               notInGroupRowView["FirstName"].ToString() + " " + notInGroupRowView["LastName"].ToString() }));
        }
    }