如何使用列表框将文本文件字符串发送到文本框?

How to send textfile string to textbox using listbox?

我正在处理的 Windows 表单应用程序项目要求我用文本文件中的值填充 4 个文本框。 在文本文件中,每一行包含每个文本框的一个词,由 space 分隔。 (例如,第一行可以说 "cat fish dog horse",第二行可以说 "a b c d")

列表框包含每行的第一个单词。 (运行同样的例子,列表框会包含"cat"和"a"。)

因此,我将双击列表框中的一个值,然后 运行 使用流阅读器在文本文件中进行搜索,select 包含 selected 项的行,将它放在一个字符串数组中,根据间距将其分成4个元素,并将它们分别放入4个文本框中。

虽然还不能正常工作,有什么建议吗?

       private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)//list double click
    {
        AccountBox.Clear();
        EmailBox.Clear();
        UserBox.Clear();
        PassBox.Clear(); //to reset boxes

        string accountName = listBox1.GetItemText(listBox1.SelectedItem);
        AccountBox.Text = accountName;

        System.IO.StreamReader account = new System.IO.StreamReader("record.txt");

        var lineCount = File.ReadLines("record.txt").Count(); 
        int lines = Convert.ToInt32(lineCount);
        for (int i = 0; i < lines; i++)

       {
        if (account.ReadLine().Contains(AccountBox.Text))
            {
                string[] words;

                words = account.ReadLine().Split(' ');

                AccountBox.Text = words[0];
                EmailBox.Text = words[1];
                UserBox.Text = words[2];
                PassBox.Text = words[3]; 
            }
            else
            {
                break;
            }
        }

因为你是用文件做记账,所以我假设里面的记录一定不会太多,所以你可以很容易地一次读取所有记录并在内存中进行比较,这样会更快更容易:

string accountName = listBox1.GetItemText(listBox1.SelectedItem);
AccountBox.Text = accountName;
string[] lines = File.ReadAllLines("record.txt");
string account = lines.Where(l=>l.Split(' ')[0]==accountName).FirstOrDefault();

if(account!=null)
{
    string[] words = account.Split(' ');
    AccountBox.Text = words[0];
    EmailBox.Text = words[1];
    UserBox.Text = words[2];
    PassBox.Text = words[3]; 
}