来自文本文件的组合框值

时间:2012-07-12 09:37:51

标签: vb.net visual-studio combobox text-files vb.net-2010

希望人们可以提供帮助!

我正在尝试创建一个组合框,其中填充了使用分隔符的文本文件中的信息作为分隔符。 IE

对象A,为研究所,N,即,如图5所示,moretext

我需要在整数/布尔/字符串之间的各个区域..但是我在使代码正确地运行时遇到了问题

我在网上搜索过,发现了这段代码,但它对我不起作用。也许我是愚蠢但希望有人可以帮助我。帮助我哦互联网的大师!

Public Sub meritlist()
    Dim looksups As New ArrayList
    ' This call is required by the Windows Form Designer.
    InitializeComponent()

    Dim rdr As IO.StreamReader = IO.File.OpenText(c:merits.txt")
    While Not rdr.EndOfStream
        Dim line As String = rdr.ReadLine()

        'Split the line by a comma:
        Dim arrayList = line.Split(",")

        'Get the right values: break down is as: Merit Name,Type,Shared,Carthan,Max,Pre-Req
        Dim meritname As Integer = arrayList(0)
        Dim merittype As String = arrayList(1)
        Dim meritshared As Boolean = arrayList(2)
        Dim carthan As String = arrayList(3)
        Dim meritmax As Integer = arrayList(4)
        Dim prereq As String = arrayList(5)

        cmoMRDro.Items.Add(New lookups(arrayList(0), arrayList(1)))

    End While
    rdr.Close()
End Sub

1 个答案:

答案 0 :(得分:1)

我建议有4件事。

  1. 使用TextFieldParser类读取分隔/固定宽度的文本文件。他们更专业地完成这项工作,并且已经有了正确处理它的代码。

  2. 不需要拨打InitializeComponent

  3. 创建一个结构/类来存储您的订单项,而不是原始变量。通过这种方式,您可以更有条理地使用它。

  4. 使用该结构/类的List代替ArrayList

  5. 虽然您已经在做的事情可以通过一些修改来纠正,但我会这样做,保留我上面给出的所有建议。所以你可以看到它之后变得多么容易:

    Structure MeritListType
        Dim meritname As Integer
        Dim merittype As String
        Dim meritshared As Boolean
        Dim carthan As String
        Dim meritmax As Integer
        Dim prereq As String
    
        Public Sub New(ByVal data() As String)
            meritname = Integer.Parse(data(0))
            merittype = data(1)
            meritshared = Boolean.Parse(data(2))
            carthan = data(3)
            meritmax = Integer.Parse(data(4))
            prereq = data(5)
        End Sub
    End Structure
    
    Public Sub MeritList()
        Dim FileData As New List(Of MeritListType)
        Dim tfp As New FileIO.TextFieldParser("c:\merits.txt")
        tfp.TextFieldType = FileIO.FieldType.Delimited
        tfp.SetDelimiters(",")
        While Not tfp.EndOfData
            FileData.Add(New MeritListType(tfp.ReadFields))
        End While
        tfp.Close()
    
        '' you have the records in FileData
        '' do whaever you want to do with it here now
    
    End Sub