如何使用文本文件从comobobox自动填充文本框

时间:2017-06-12 08:14:22

标签: vb.net combobox

我目前正在VB中创建一个表单,该表单使用文本文件收集组合框的信息,然后自动使用文本文件中以逗号分隔的下一个单词来自动填充文本框。 但是我写的当前代码显示了组合框的列表,但总是自动用第二行中的第二个单词填充文本框,并且在我从组合框中选择另一个选项后,有人可以帮助改变文本框吗?

对不起,如果这不是很清楚。

我的文本文件采用以下格式:

Robert,5 BellView Road

Martin,BellView路6号

... Ect的

我的代码如下:

Dim LineString As String

Dim FieldString As String()

    Try

        Dim ContactInfoStreamReader As StreamReader = New StreamReader("C:\temp\test1.txt")

        Do Until ContactInfoStreamReader.Peek = -1

            LineString = ContactInfoStreamReader.ReadLine()
            FieldString = LineString.Split(CChar(","))
            LineString = FieldString(0)
            ComboBox1.Items.Add(LineString)
            Loop
        RichTextBox2.Text = FieldString(1)
        ContactInfoStreamReader.Close()
    Catch ex As Exception
        MsgBox("""Customers Name & Address.txt"" file was not found")
    End Try

1 个答案:

答案 0 :(得分:0)

好的,我知道你提供了代码,但这就是我要做的事情。

首先,我们制作Person Class并创建Person List来存储每个Person


之后,我们将文本文件读取/加载到string array,然后我们使用Linq拆分逗号所在的文本文件行,并将名称和地址分为两个键,一个是{{ 1}}而另一个是NAME
一旦完成,我们遍历每个项目并创建一个值为ADDRESS的新Personvalue.NAME代表人名和地址,并将此人的姓名添加到Value.Address中,最后我们添加ComboBox Event更改了所选combobox的{​​{1}}文字与为存储每个Textbox's而创建的ComboBox's Index相匹配

List of People

编辑:
这是我格式化文本文件的方式。
Person
Public Class Form1 Dim People As New List(Of Person) Private Sub ComboBox1_SelectedValueChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedValueChanged Try TextBox1.Text = People(ComboBox1.SelectedIndex).address Catch ''this will prevent errors if there is a name with no address TextBox1.Text = "" End Try End Sub Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load ''This is the location I used, feel free to change it here. Dim location As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) Dim fileName As String = "test1.txt" Dim path As String = System.IO.Path.Combine(location, fileName) Dim query = From line In System.IO.File.ReadAllLines(path) Let val = line.Split(",") Select New With {Key .NAME = val(0), Key .ADDRESS = val(1)} For Each value In query Dim p = New Person(value.NAME, value.ADDRESS) People.Add(p) ComboBox1.Items.Add(value.NAME) Next ''ADD OTHER COMBOBOX ITEMS HERE IF NEED BE, SO EVERYTHING IS IN ORDER ComboBox1.Items.Add("ANDREW") End Sub End Class Class Person Public Property name() As String Public Property address() As String Public Sub New(name As String, address As String) Me.name = name Me.address = address End Sub End Class