简体   繁体   中英

read items from listbox

I have a listbox with 1 or more textfiles, which im going to print as commands. 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" ?

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

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