将文本文件的某些行放入可编辑的列表框中

时间:2014-03-14 19:31:03

标签: c# streamreader streamwriter

所以我想把某些行放到一个文本框中,比如我使用"搜索功能"要搜索事务ID,它将查看transactions.txt文件并查找事务ID并读取其下显示事务详细信息的6行,一旦发现这将转到列表框,然后您可以编辑事务。

我想知道您是否会使用循环和数组来执行此操作,有人可以告诉我如何,谢谢!

继承我目前的代码:

  //Creates a textfile with details of the transaction
    public void CreateFile()
{
     StreamWriter outputFile;
        outputFile = File.AppendText("Transactions.txt");
        outputFile.WriteLine("Investor :" +" " + InvestorNameLabel.Text);
        outputFile.WriteLine("Initial Amount" + " " +AmountLabel.Text);
        outputFile.WriteLine("Date Invested" +" " +DateLabel.Text);
        outputFile.WriteLine("Period Chosen" + " "+DaysInvestedLabel.Text);
        outputFile.WriteLine("Rate Chosen" + " " + RateLabel.Text);
        outputFile.WriteLine("Total Interest" + " " +InterestAmountLabel.Text);
        outputFile.WriteLine("Transaction Number :" + " " + TransactionIDLabel.Text);
        outputFile.Close();

        MessageBox.Show("Transaction file for Transaction: " + TransactionIDLabel.Text + " " +"Was Created", "Transaction File");
       }

       //puts all transactions in listbox
       //needs to be able to find certain transactions

        private void button1_Click(object sender, EventArgs e)
    {

        using (StreamReader sr = new StreamReader("transactions.txt"))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                listBox1.Items.Add(line);
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

试试这个:

string ID = "23";
bool idFound=false;
int count = 0;
foreach (var line in File.ReadLines("transactions.txt"))
{
    if (idFound  && count < 6)
    {
        listBox1.Items.Add(line);
        count++;
    }
    if(line.Contains(ID))//if you wantto match exactly use if(line.Equals(ID))
    {
        idFound = true;
    }
}