[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Passing variables between methods in C#

Posted on 2006-05-30
4
Medium Priority
?
572 Views
Last Modified: 2008-01-09
Hello,

Does anybody know how to pass variables between methods in C#?

The problem is that if a variable is local to the method it was created then it can not be passed to another method.

I tried using a public accessor prefix but that did not help.

I would like to avoid putting it in session if at all possible.

Here is the code I'm working on. Please check out the comments:


======================================================

private void HarrisNeighborhoodsEngage(object sender, System.EventArgs e)
{
      string CONN = ConfigurationSettings.AppSettings ["DB_CONN"];
 
            SqlConnection conn = new SqlConnection(CONN);
            SqlCommand command = new SqlCommand("MLS_HCAD", conn);
            command.CommandTimeout = 0;
            command.CommandType = CommandType.StoredProcedure;

            try
            {
                  conn.Open();
                  SqlDataReader reader = command.ExecuteReader();
                  DataSet dsTemp = new DataSet();
                  DataTable Tables = new DataTable();
                  dsTemp.Tables.Add(Tables);
                  dsTemp.Tables[0].Columns.Add( "val", System.Type.GetType ("System.String" ) );
                  while (reader.Read())
                  {

                        string currentNeighborhoodCode = reader["txroll_NeighborhoodCode"] as String;

                        // ************************************************************
                        // This is where I want to pass the cadAcct variable
                                                               // *************************************************************
                        ExportCRVariables(currentNeighborhoodCode);  // this is where cadAcct is being created.

                        ExportToPdf();                    // I want to put it here like this: ExportToPdf(string cadAcct).

                  }

            }
            catch(Exception ex)
            {
                  string exception = ex.Message;  
            }

            finally
            {
                  conn.Close();
                  command.Dispose();  
            }

      } // ends private void HarrisNeighborhoodsEngage()


      private void ExportToPdf()
      {
            string ExportPath;
            ExportPath = ConfigurationSettings.AppSettings["PAPERWISE_PATH"];
            if (Directory.Exists(ExportPath) == false) Directory.CreateDirectory(ExportPath);
            crDiskFileDestinationOptions = new DiskFileDestinationOptions();
            crExportOptions = oRpt.ExportOptions;

            string today = DateTime.Now.ToString("MMMMddyyyy_HHmm");
            string fullFileName = ExportPath+today+"_NeighborhoodReport.pdf";
            crDiskFileDestinationOptions.DiskFileName = fullFileName ;
            crExportOptions.DestinationOptions = crDiskFileDestinationOptions;
            crExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
            crExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
            try
            {
                  oRpt.Export();
            }
            catch (Exception err)
            {
                  Response.Write("<BR>");
                  Response.Write(err.Message.ToString ());
            }
      

      } // ends private void ExportToPdf()




      private void ExportCRVariables(string currentNeighborhoodCode)
      {      
            oRpt = new rptSales();
            string CONN = ConfigurationSettings.AppSettings ["DB_CONN"];
            SqlConnection connObj = new SqlConnection(CONN);
            SqlCommand cmdObj = new SqlCommand("MLS_HCAD_ProcessPerNeighborhood", connObj);
            cmdObj.CommandType = CommandType.StoredProcedure ;
            cmdObj.Parameters.Add(new SqlParameter("@strNeighborhoodCode", currentNeighborhoodCode));
            
            SqlDataAdapter da = new SqlDataAdapter ( cmdObj ) ;
            DataSet dataSet = new DataSet();
            da.SelectCommand.CommandTimeout = 0;
            da.Fill(dataSet, "MLS");

            //****************************************************************************
                                 //        This is where the variable cadAcct is getting created
                                 // ***************************************************************************
            string cadAcct = dataSet.Tables["MLS"].Rows[0]["cad_account_number"]as String;
            
            oRpt.SetDataSource(dataSet);
            CrystalReportViewer1.ReportSource = oRpt;
            oRpt.PrintOptions.PaperOrientation = PaperOrientation.Landscape;
            oRpt.PrintOptions.PaperSize = PaperSize.PaperLetter;
      }


}

=======================================================

Any help is greatly appreciated.

-Eddie
0
Comment
Question by:FastEddie___
  • 2
  • 2
4 Comments
 
LVL 37

Accepted Solution

by:
gregoryyoung earned 2000 total points
ID: 16793170
                   // ************************************************************
                    // This is where I want to pass the cadAcct variable
                                                               // *************************************************************
                    string cadAcct = ExportCRVariables(currentNeighborhoodCode);  // this is where cadAcct is being created.

                    ExportToPdf(cadAcct);                    // I want to put it here like this: ExportToPdf(string cadAcct).

    private string ExportCRVariables(string currentNeighborhoodCode)
     {    
          oRpt = new rptSales();
          string CONN = ConfigurationSettings.AppSettings ["DB_CONN"];
          SqlConnection connObj = new SqlConnection(CONN);
          SqlCommand cmdObj = new SqlCommand("MLS_HCAD_ProcessPerNeighborhood", connObj);
          cmdObj.CommandType = CommandType.StoredProcedure ;
          cmdObj.Parameters.Add(new SqlParameter("@strNeighborhoodCode", currentNeighborhoodCode));
         
          SqlDataAdapter da = new SqlDataAdapter ( cmdObj ) ;
          DataSet dataSet = new DataSet();
          da.SelectCommand.CommandTimeout = 0;
          da.Fill(dataSet, "MLS");

          //****************************************************************************
                                 //        This is where the variable cadAcct is getting created
                                 // ***************************************************************************
          string cadAcct = dataSet.Tables["MLS"].Rows[0]["cad_account_number"]as String;
         
          oRpt.SetDataSource(dataSet);
          CrystalReportViewer1.ReportSource = oRpt;
          oRpt.PrintOptions.PaperOrientation = PaperOrientation.Landscape;
          oRpt.PrintOptions.PaperSize = PaperSize.PaperLetter;
          return cadAcct;
     }
0
 

Author Comment

by:FastEddie___
ID: 16793485
I have added :  ExportToPdf(cadAcct);

Put a   return cadAcct;    statement at the end of ExportCRVariables( ) method.

Changed the ExportCRVariables( ) mehtod from void to string.

And added a parameter to the ExportToPDF mehtod.

    ExportToPdf(string cadAcct)
    {
        ....
    }

But I still get this error:

c:\inetpub\wwwroot\MLS2\dsp_AllNeighborhoods.aspx.cs(97): The name 'cadAcct' does not exist in the class or namespace 'MLS2.dsp_AllNeighborhoods'

Line 97 is this:    ExportToPdf(cadAcct);

Any ideas on how to resolve this one.

Thanks.

-Eddie


Here is the code I have so far:  

==============================================================

namespace MLS2
{
      /// <summary>
      /// Summary description for dsp_AllNeighborhoods.
      /// </summary>
      public class dsp_AllNeighborhoods : System.Web.UI.Page
      {
            private rptSales oRpt = new rptSales();

            // EXPORT CR Variables
            private ExportOptions crExportOptions;
            private DiskFileDestinationOptions crDiskFileDestinationOptions;

            protected System.Web.UI.WebControls.Button cmdAllNeighborhoods;
            protected System.Web.UI.WebControls.DataGrid DataGrid1;
            protected CrystalDecisions.Web.CrystalReportViewer CrystalReportViewer1;
            protected System.Web.UI.WebControls.Label Label1;

            //public rptSales oRpt = null; //delcare a report object


            private void Page_Load(object sender, System.EventArgs e)
            {
                  // Put user code to initialize the page here
            }

            #region Web Form Designer generated code
            override protected void OnInit(EventArgs e)
            {
                  //
                  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                  //
                  InitializeComponent();
                  base.OnInit(e);
            }
            
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {    
                  this.cmdAllNeighborhoods.Click += new System.EventHandler(this.HarrisNeighborhoodsEngage);
                  this.Load += new System.EventHandler(this.Page_Load);

            }
            #endregion




            private void HarrisNeighborhoodsEngage(object sender, System.EventArgs e)
            {
                  string CONN = ConfigurationSettings.AppSettings ["DB_CONN"];
 
                  // get list of neighborhood codes
                  SqlConnection conn = new SqlConnection(CONN);
                  SqlCommand command = new SqlCommand("MLS_HCAD", conn);
                  command.CommandTimeout = 0;
                  command.CommandType = CommandType.StoredProcedure;

                  try
                  {
                        conn.Open();
                        SqlDataReader reader = command.ExecuteReader();
                        DataSet dsTemp = new DataSet();
                        DataTable Tables = new DataTable();
                        dsTemp.Tables.Add(Tables);
                        dsTemp.Tables[0].Columns.Add( "val", System.Type.GetType ("System.String" ) );
                        while (reader.Read())
                        {
 
                              string currentNeighborhoodCode = reader["txroll_NeighborhoodCode"] as String;

                              // Send the code the Export CR Variables method
                              ExportCRVariables(currentNeighborhoodCode);
                              ExportToPdf(cadAcct);
 
                        }

                  }
                  catch(Exception ex)
                  {
                        // Logg the exception in the database
                        string exception = ex.Message;  
                  }

                  finally
                  {
                        conn.Close();
                        command.Dispose();  
                  }

            } // ends private void HarrisNeighborhoodsEngage()

            private string ExportCRVariables(string currentNeighborhoodCode)
            {
                  
                  oRpt = new rptSales(); //instantiate report object

                  // run a second SP, fill a dataset, create report
                  string CONN = ConfigurationSettings.AppSettings ["DB_CONN"];
                  SqlConnection connObj = new SqlConnection(CONN);
                  SqlCommand cmdObj = new SqlCommand("MLS_HCAD_ProcessPerNeighborhood", connObj);
                  cmdObj.CommandType = CommandType.StoredProcedure ;
                  cmdObj.Parameters.Add(new SqlParameter("@strNeighborhoodCode", currentNeighborhoodCode));
             
                  SqlDataAdapter da = new SqlDataAdapter ( cmdObj ) ;
                  DataSet dataSet = new DataSet();
                  da.SelectCommand.CommandTimeout = 0;
                  da.Fill(dataSet, "MLS");

                  //get unique cad account number to be used in report name string.
                  string cadAcct = dataSet.Tables["MLS"].Rows[0]["cad_account_number"]as String;
             
                  /* Use Report Engine object model to pass populated dataset to report */
                  oRpt.SetDataSource(dataSet);
             
                  /* bind report object containing data to the Crystal Web Forms Viewer */
                  CrystalReportViewer1.ReportSource = oRpt;
                  oRpt.PrintOptions.PaperOrientation = PaperOrientation.Landscape;
                  oRpt.PrintOptions.PaperSize = PaperSize.PaperLetter;

                  return cadAcct;

            }



            private void ExportToPdf(string cadAcct)
            {
                  // ****************************************************
                  // start export report of pdf to local file system
                  // ****************************************************
                  //Check to see if the application directory has a subdirectory called "Export".
                  //If not, create the directory since exported files will be placed here.
                  //This uses the Directory class of the System.IO namespace.
                  string ExportPath;
                  ExportPath = ConfigurationSettings.AppSettings["PAPERWISE_PATH"];
                  if (Directory.Exists(ExportPath) == false) Directory.CreateDirectory(ExportPath);
 
                  // First we must create a new instance of the diskfiledestinationoptions class and
                  // set variable called crExportOptions to the exportoptions class of the reportdocument.
                  crDiskFileDestinationOptions = new DiskFileDestinationOptions();
                  crExportOptions = oRpt.ExportOptions;
 
                  //--------------------------------------------------------------------
                  //Export to PDF
                  //append a filename to the export path and set this file as the filename property for


                  //the DestinationOptions class
                  string today = DateTime.Now.ToString("MMMMddyyyy_HHmm");
                  string fullFileName = ExportPath+today+"_NeighborhoodReport.pdf";
                  crDiskFileDestinationOptions.DiskFileName = fullFileName ;
                  //set the required report ExportOptions properties
                  crExportOptions.DestinationOptions = crDiskFileDestinationOptions;
                  crExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
                  crExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
                  //Once the export options have been set for the report, the report can be exported.
                  //The Export command does not take any arguments
                  try
                  {
                        // Export the report
                        oRpt.Export();
                  }
                  catch (Exception err)
                  {
                        Response.Write("<BR>");
                        Response.Write(err.Message.ToString ());
                  }
                  // ****************************************************
                  // end export report of pdf to local file system
                  // ****************************************************

            } // ends private void ExportToPdf()






      }
}

=======================================================================
0
 
LVL 37

Expert Comment

by:gregoryyoung
ID: 16793513
                        ExportCRVariables(currentNeighborhoodCode);

to

string cadAccount = ExportCRVariables(currentNeighborhoodCode);  //this function returns the cadAccount.
0
 

Author Comment

by:FastEddie___
ID: 16794104
That did the trick.

Thanks gregoryyoung.

-Eddie

0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…
Suggested Courses

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question