简体   繁体   中英

How to send textfile string to textbox using listbox?

The Windows Form application project I'm working on requires me to fill 4 textboxes with values in a text file. In the textfile, every line contains a word for each textbox, separated by a space. (For example, the first line could say "cat fish dog horse" and the second line could say "abcd")

The listbox contains the first word of every line. (Running with the same example, the list box will contain "cat" and "a".)

So I'll double click on a value in the listbox, and run a search in the textfile using streamreader, select the line that contains the selected item, place it in a string array, split it into 4 elements based on the spacing, and place them into the 4 respective textboxes.

It doesn't work right yet though, any suggestions?

       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;
            }
        }

As you are using file as accounting so I assume that there must not be much records in it, So you can easily read all records at once and compare them in memory which will be much faster and easier:

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]; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM