Home > Back-end >  C# forms: how do I print out a CSV file which is selected using a different button
C# forms: how do I print out a CSV file which is selected using a different button

Time:04-08

Goal: Direct print a CSV file which is selected from another button on my forms application

Problem: I don't know how to tell amy btnPrintFile_click method the FileName coming from another method in form1.cs

Any help would be appreciated, Im new to forms in c#

public void openCVSFile(object sender, EventArgs e)


{
     OpenFileDialog ofd = new OpenFileDialog();
     ofd.Multiselect = false;
     ofd.Filter = "CSV files (*.csv)|*.csv";
     ofd.FilterIndex = 1;
     if(ofd.ShowDialog() == DialogResult.OK)
     {
         txtAddressCount.Text = ("Address count: "  ofd.FileName);
     }
 }

 private void btnPrintFile_Click(object sender, EventArgs e)
 {
     try
     {
         streamToPrint = new StreamReader(ofd.FileName);
         try
         {
             printFont = new Font("Arial", 10);
             PrintDocument pd = new PrintDocument();
             pd.PrintPage  = new PrintPageEventHandler
                (this.pd_PrintPage);
             pd.Print();
         }
         finally
         {
             streamToPrint.Close();
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }

For reference I'm using this article from Microsoft

enter image description here

And rename it so it is called ofd by altering the (Name) line in the property grid:

enter image description here

Either of these ways make it accessible to all methods in the class. Doing it the visual way probably makes life easier in terms of setting other properties like the initial folder, file filter etc

  • Related