数组到组合框?

时间:2013-01-27 00:27:13

标签: vb.net

我有这个结构,有一个结构类型的数组。

Structure CustomerAccountsRec
    Dim strFirstName As String
    Dim strLastName As String
    Dim intAge As Integer
    Dim strAddress As String
    Dim strTown As String
    Dim strPostcode As String
    Dim strCusNum As String
End Structure

Public strCusArray() As CustomerAccountsRec

我希望能够获取数组的strCusNum并用它填充组合框,但无法弄清楚如何。有什么帮助吗?

4 个答案:

答案 0 :(得分:3)

您还可以覆盖结构中的ToString方法,如上所述。我还创建了一个List(Of CustomerAccountsRec),这使得添加值更容易,然后我将列表绑定到ComboBox's DataSource

Public Class Form1
    Structure CustomerAccountsRec
        Dim strFirstName As String
        Dim strLastName As String
        Dim intAge As Integer
        Dim strAddress As String
        Dim strTown As String
        Dim strPostcode As String
        Dim strCusNum As String
        Public Overrides Function ToString() As String
            Return strCusNum
        End Function
    End Structure

    Public strCusArray As List(Of CustomerAccountsRec) = New List(Of CustomerAccountsRec)

    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

        Dim carec As CustomerAccountsRec = New CustomerAccountsRec
        carec.strFirstName = "Hello"
        carec.strLastName = "World"
        carec.strCusNum = "Hello World"
        carec.strTown = "AnyTown"
        carec.strAddress = "AnyStreet"
        carec.strCusNum = "12345678"
        strCusArray.Add(carec)
        ComboBox1.DataSource = strCusArray

    End Sub
End Class

答案 1 :(得分:0)

您可以使用ComboBox.Items.Add方法添加项目,并且要正确显示结构,您必须覆盖它的ToString方法。

请参阅:

ComboBox: Adding Text and Value to an Item (no Binding Source)

how to add value to combobox item

答案 2 :(得分:0)

您可以使用LINQ获取包含要显示的项目的数组,然后将该数组绑定到ComboBox

Dim combo as New ComboBox
combo.DataSource = strCusArray.Select(Function(f) f.strCusNum).ToArray()

答案 3 :(得分:0)

如果我理解你的问题。

Public strCusArray() As CustomerAccountsRec的实际结果为空,因此我们无法使用此功能将CustomerAccountsRec中的所有项目添加到ComboBox

List Structure Structure CustomerAccountsRec Dim strFirstName As String Dim strLastName As String Dim intAge As Integer Dim strAddress As String Dim strTown As String Dim strPostcode As String Dim strCusNum As String End Structure Dim fi As FieldInfo() = GetType(CustomerAccountsRec).GetFields(BindingFlags.[Public] Or BindingFlags.Instance) For Each info As FieldInfo In fi ComboBox2.Items.Add(info.Name) Next 中的所有项目,我们需要使用 System.Reflection Namespace

{{1}}

来源:C# version