从列表框中读取项目

时间:2012-08-15 09:29:16

标签: c# listbox streamreader

我有一个包含一个或多个文本文件的列表框,我将打印为命令。 但我不知道如何从列表框中读取流读取器?

到目前为止,我得到了这个。:

public void OutputBtn_Click(object sender, EventArgs e)
{
    PrintDocument PrintD = new PrintDocument();
    PrintD.PrintPage += new PrintPageEventHandler(this.PrintDocument_PrintPage);
    StreamReader SR = new StreamReader("C:\\myfile.txt");
    PrintD.Print();

}

有没有我可以改变“C:\ myfile.txt”或者我是否必须使用“foreach”?

1 个答案:

答案 0 :(得分:0)

你想要这样的东西吗?我不完全理解这个问题

string[] fileEntries = Directory.GetFiles("C:\\temp\\").Where(p => 
                                 p.EndsWith(".txt")).ToArray<string>();
foreach (string fileName in fileEntries)
{
    lb.Items.Add(new ListItem(fileName, fileName);
}

好的,你的列表框中有文件名吗?

private StreamReader sr;

public void OutputBtn_Click(object sender, EventArgs e)
{
    foreach(var li in lb.Items)
    {
        PrintDocument PrintD = new PrintDocument();
        PrintD.PrintPage += new PrintPageEventHandler(this.PrintDocument_PrintPage);
        sr = new StreamReader(li.ToString());
        PrintD.Print();        
    }
}

private void PrintDocument_PrintPage(object sender, PrintPageEventArgs ev) 
{
     float linesPerPage = 0;
     float yPos =  0;
     int count = 0;
     float leftMargin = ev.MarginBounds.Left;
     float topMargin = ev.MarginBounds.Top;
     String line = null;

     // Calculate the number of lines per page.
     linesPerPage = ev.MarginBounds.Height  / 
        printFont.GetHeight(ev.Graphics) ;

     // Iterate over the file, printing each line.
     while (count < linesPerPage && ((line = sr.ReadLine()) != null)) 
     {
        yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
        ev.Graphics.DrawString (line, printFont, Brushes.Black, 
           leftMargin, yPos, new StringFormat());
        count++;
     }

     // If more lines exist, print another page.
     if (line != null) 
        ev.HasMorePages = true;
     else 
        ev.HasMorePages = false;
}