简体   繁体   English

从列表框中读取项目

[英]read items from listbox

I have a listbox with 1 or more textfiles, which im going to print as commands. 我有一个包含1个或多个文本文件的列表框,我将它们打印为命令。 but I dont know how to make the streamreader read from listbox ? 但我不知道如何使流阅读器从列表框中读取?

so far I got this.: 到目前为止,我明白了:

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();

}

is there enyway I can change "C:\\myfile.txt" or do I have to use "foreach" ? 我可以更改“ C:\\ myfile.txt”还是必须使用“ foreach”吗?

Do you want something like this? 你想要这样的东西吗? I don't fully understand the question 我不完全明白这个问题

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

Ok so you have the listbox filled with filenames? 好的,这样您的列表框中就充满了文件名吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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