Click here to Skip to main content
15,881,757 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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

Could someone help me? Im new to forms in c#

Code

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


What I have tried:

I tried making openCVSFile method return the filename but that doesnt work
Posted
Updated 7-Apr-22 19:59pm
v2

1 solution

Create a class level private variable, and put the path in there:
private string pathToFile = null;
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);
         pathToFile = ofd.FileName;
     }
 }

 private void btnPrintFile_Click(object sender, EventArgs e)
 {
     if (pathToFile == null) return;
     try
     {
         streamToPrint = new StreamReader(pathToFile);
         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);
     }
 }
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900