【问题标题】:VB: populating a combobox with values from a tableVB:使用表中的值填充组合框
【发布时间】:2014-12-04 17:32:32
【问题描述】:

我有下表:

    Public table As New DataTable

    table.Columns.Add("#", GetType(Integer))
    table.Columns.Add("Name", GetType(String))
    table.Columns.Add("Exp", GetType(Integer))
    table.Columns.Add("HP", GetType(Integer))
    table.Columns.Add("At", GetType(Integer))
    table.Columns.Add("De", GetType(Integer))
    table.Columns.Add("SA", GetType(Integer))
    table.Columns.Add("SD", GetType(Integer))
    table.Columns.Add("Sp", GetType(Integer))
    table.Columns.Add("Tot", GetType(Integer))

    table.Rows.Add(1, "One", 64, 0, 0, 0, 1, 0, 0, 1)
    table.Rows.Add(2, "Two", 142, 0, 0, 0, 1, 1, 0, 2)
    table.Rows.Add(3, "Three", 236, 0, 0, 0, 2, 1, 0, 3)

..........

该表有数百个条目。

我想用Name 字段的所有条目填充一个组合框,按字母顺序或#(由用户定义)排序。

有没有办法轻松做到这一点,例如类似于

combobox.Items.AddRange(table.Colums(2))

?

【问题讨论】:

    标签: vb.net vba visual-studio-2013 vb6


    【解决方案1】:

    您可以使用 LINQ 获取所需的条目:

    Dim values = table.AsEnumerable().
        OrderBy(Function(row) row.Field(Of Integer)("#")).
        Select(Function(row) row.Field(Of String)("Name")).
        ToArray()
    

    然后将它们添加到您的组合框中:

    combobox.Items.AddRange(values)
    

    【讨论】:

    • 谢谢,这成功了!但是,在 AddRange() 中,必须使用 values 而不是 val
    • @Mierzen 当然。我更正了答案的那部分。
    【解决方案2】:

    在下面的示例中,我假设一个名为ComboBox1 的组合框位于Sheet1。 我还假设该表名为Table1。您将需要根据需要进行调整。

    此解决方案是 VBA。

    Sub SortedComboFromTableColumn()
        Dim rng As Range
    
        With CreateObject("System.Collections.ArrayList")
            For Each rng In Range("Table1[Name]")
                .Add rng.Value
            Next
            .Sort
    
            Sheets(1).ComboBox1.List = Application.Transpose(.toarray())
        End With
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-30
      • 1970-01-01
      相关资源
      最近更新 更多