C# forms: how do I print out a CSV file which is selected using a different button

Advertisements

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

https://docs.microsoft.com/en-us/dotnet/api/system.drawing.printing.printdocument?redirectedfrom=MSDN&view=dotnet-plat-ext-6.0

>Solution :

public void openCVSFile(object sender, EventArgs e)
{
   OpenFileDialog ofd = new OpenFileDialog();
   ...
}

...

private void btnPrintFile_Click(object sender, EventArgs e)
{
 try
 {
     streamToPrint = new StreamReader(ofd.FileName);
                                      ^^^
                        ofd was declared in the other method 

Im new to forms in c#

This isn’t about forms; you can never reach a variable declared inside one method, from another method.. the variable has to be passed from one method to the other, or it has to be declared at a scope that both methods can access.

Declare your OpenFileDialog under the class instead:

class YourForm: Form{

  private OpenFileDialog ofd = new OpenFileDialog();

or drop it onto the form in the designer so it appears in the tray under the form view:

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

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

Leave a ReplyCancel reply