0

我被要求在 ComboBox 中添加一个“ALL”项,该查询被分配为其数据源,项“ALL”应该是控件中看到的第一个项

        Dim qryEmp = From emp In db.Members.ToList
                        Order By emp.LogonId Ascending
                        Select New GPUserQueryResult With {
                            .LoginId = emp.LogonId,
                            .FullName = GetUserName(emp.LogonId)
                        }

我最终使用的代码是这样的:

            Dim allUser() As GPUserQueryResult = {New GPUserQueryResult With {.LoginId = -1, .FullName = AllValues}}
            Dim addEmpty As IEnumerable(Of GPUserQueryResult) = allUser

            Dim allRecs As IEnumerable(Of GPUserQueryResult) = addEmpty.Union(qryEmp)

            EmpList = allRecs.ToDictionary(Function(x) x.LoginId, Function(x) x.FullName)

起初虽然我试过这个:

            Dim allUser() As GPUserQueryResult = {New GPUserQueryResult With {.LoginId = -1, .FullName = AllValues}}
            Dim addEmpty As IEnumerable(Of GPUserQueryResult) = allUser

            Dim allRecs As IEnumerable(Of GPUserQueryResult) = qryEmp.Union(addEmpty)

            EmpList = allRecs.ToDictionary(Function(x) x.LoginId, Function(x) x.FullName)
            EmpList.Keys.OrderBy(Function(x) x)

但是“ALL”项目始终是最后一个,即使我尝试使用 OrderBy 方法,有人可以解释为什么吗?如果这是实现目标的最佳方式

4

1 回答 1

1

我在上面尝试了您的代码,并且按预期首先显示了“ALL”项目。不知道为什么它对你不起作用。但是,另一种更简单的方法可以满足您的需要:

Dim qryEmp = .... ' your existing linq to retrieve employees

现在您需要将“ALL”项目插入到第一个位置。首先将转换qryEmp为 List 对象:

Dim EmpList = qryEmp.ToList()

在位置 0 处插入“ALL”项:

EmpList.Insert(0, New GPUserQueryResult With {.LoginId = -1, .FullName = AllValues})

将列表绑定到 ComboBox:

ComboBox1.DisplayMember = "FullName"
ComboBox1.ValueMember = "LoginId"
ComboBox1.DataSource = New BindingSource(EmpList, Nothing)

样本:

在此处输入图像描述

于 2013-10-05T03:16:49.953 回答