Colin
Colin

Reputation: 3

Read Same Text File in Different Methods

In the BtnNext_Click method it's just reading from the text file like it was a different text file, and not from the one that already was opened. It does not go from line to line. I need help

Here is the code:

public void ScrubData()
{           
    string FileName1;
    string FilePath1;

    // Display an OpenFile Dialog box for user
    OpenFileDialog openFileDialog1 = new OpenFileDialog();
    openFileDialog1.Filter = "txt Files|*.txt";
    openFileDialog1.Title = "Select a txt File";

    // Show the Dialog. If user clicked OK in the dialog
    if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        try
        {
            String strFileName = openFileDialog1.FileName;
            String strFilePath = System.IO.Path.GetDirectoryName(strFileName);
            String fileName = System.IO.Path.GetFileNameWithoutExtension(strFileName);
            String strFileNameAndPathNew = strFilePath +
                openFileDialog1.InitialDirectory + "\\" + fileName + "_scrubbed.txt";

            // If scrubbed file exists, delete it first
            if (System.IO.File.Exists(strFileNameAndPathNew))
            {
                System.IO.File.Delete(strFileNameAndPathNew);
            } // End IF
            if (System.IO.File.Exists(strFileName))
            {
                int lineCount = System.IO.File.ReadAllLines(strFileName).Length;
                System.IO.StreamReader file = new System.IO.StreamReader(strFileName);
                // Status label 
                LblStatus.Text = "File Loaded Successfully";
                LblStatus.Visible = true;
                string line;
                while ((line = file.ReadLine()) != null)
                {
                    const char DELIM = '|';
                    // MessageBox.Show(line);

                    string[] word = line.Split(DELIM);
                     Txt2NormAccNum.Text = word[3];
                    //string accScrubbed = ReplaceData(word[0],"SSN");
                    Txt3NormAmnt.Text = word[4];
                    Txt4NormFirstNam.Text = word[1];
                    Txt5NormLastNam.Text = word[2];
                    Txt6NormSS.Text = word[0];
                    Txt7NormItem.Text = word[5];
                } // End WHILE
            } // End IF
            else
            {
                // Status label 
                LblStatus.Text = "File Load Failed!";
                LblStatus.Visible = true;
            } // End ELSE
            // Text box one code:
            FileName1 = openFileDialog1.FileName;
            Txt1.Text = FileName1;
            //
        } // End TRY
        catch (Exception e1)
        {
             if (e1.Source != null)
            {
                Console.WriteLine("IOException source: {0}", e1.Source);
                throw;
            } // End IF
        } // End CATCH
    } // End IF
} // End Scrub Method

I need to reuse the variables such as "strFileName" in my next method.

I am creating a previous & next buttons to cycle through each line in the text file:

public void BtnNext_Click(object sender, EventArgs e)
{
    StreamReader myReader2 = new StreamReader("colin.txt");
    string line2 = "";

    while (line2 != null)
    {
        line2 = myReader2.ReadLine();
        if (line2 != null)
        {
            const char DELIM = '|';
            // MessageBox.Show(line);
            string[] word = line2.Split(DELIM);
            Txt2NormAccNum.Text = word[3];
            Txt3NormAmnt.Text = word[4];
            Txt4NormFirstNam.Text = word[1];
            Txt5NormLastNam.Text = word[2];
            Txt6NormSS.Text = word[0];
            Txt7NormItem.Text = word[5];

            //Txt12ScrubSS.Text;
            //Txt10ScrubFirstNam.Text;
            //Txt11ScrubLastNam.Text;
            //Txt8ScrubAcctNum.Text;
            //Txt9ScrubAmt.Text;
            //Txt13ScrubItem.Text;
        }
    }
    myReader2.Close();

} // end method

If you see what Im saying: The design is: User opens file, first line of text from file is displayed on form, Then I have a 'previous" and 'next' button that I want to cycle through the lines of text from that same file.

@Tim Yeah I think I know what your saying Here look at this:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.IO;

    namespace Project2_DataScrubber
    {
public partial class Form1 : Form
{ // Begin Class #1

    public Form1()
    { // Begin Main Method


        InitializeComponent();

        // MessageBox.Show(GetRandomNumbers().ToString());


    } // End Main Method

    private void Btn4_Click(object sender, EventArgs e)
    { // Btn4 CLICK Method

        // Closes Form 1
        this.Close();
    } // End Method

    private void Btn3_Click(object sender, EventArgs e)
    { // Btn3 CLICK Method

        // Display alert message box of are you sure you want to reset the data
        DialogResult dialogResult1 = MessageBox.Show("Are you want to reset the data?", "ALERT", MessageBoxButtons.YesNo);
        if (dialogResult1 == DialogResult.Yes)
        {
            // Resets all the data, textboxes, ect
            Txt1.Text = "No file loaded.";
            Txt2NormAccNum.Clear();
            Txt3NormAmnt.Clear();
            Txt4NormFirstNam.Clear();
            Txt5NormLastNam.Clear();
            Txt6NormSS.Clear();
            Txt7NormItem.Clear();
            Txt8ScrubAcctNum.Clear();
            Txt9ScrubAmt.Clear();
            Txt10ScrubFirstNam.Clear();
            Txt11ScrubLastNam.Clear();
            Txt12ScrubSS.Clear();
            Txt13ScrubItem.Clear();
            Txt14ScrubYesNo.Clear();
            LblStatus.Visible = false;
        }
        else if (dialogResult1 == DialogResult.No)
        {
            // Do nothing
        }

    } // End Method

    public  void Btn1_Click(object sender, EventArgs e)
    { // Btn1 CLICK Method

        ScrubData();
    } // End Method

    public void Btn2_Click (object sender, EventArgs e)
    {
        if (Txt2NormAccNum.Text != "" || Txt3NormAmnt.Text != "" || Txt4NormFirstNam.Text != "" || Txt5NormLastNam.Text != "" ||
            Txt6NormSS.Text != "" || Txt7NormItem.Text != "")
        {
                                                                //
            Txt12ScrubSS.Text = GetRandomNumbers().ToString();  // Replace SS textbox
            //
            #region
            int lastNameLetters = Txt5NormLastNam.Text.Length;  //   
            string lettersTwo = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            Random randLetters = new Random();
            string randomString = "";
            for (int i = 0; i < lastNameLetters; i++)
            {                                                   // Replace Last Name
                randomString += lettersTwo
                    [randLetters.Next(0, 25)].ToString();
            }
            Txt11ScrubLastNam.Text = randomString;              //
            #endregion
            #region
            var newAccountNum = "";                             //
            int numOfCharacters = 4; // # to leave behind
            for (var i = 0; i<Txt2NormAccNum.Text.Length - numOfCharacters; i++)
            {
                newAccountNum += "X";                           // Replace Account Number
            }
            newAccountNum += Txt2NormAccNum.Text.Substring
                (Txt2NormAccNum.Text.Length - numOfCharacters);
            Txt8ScrubAcctNum.Text = newAccountNum;              //
            #endregion
            #region
            double moneyAmountDoub = 0;                         //
            string moneyAmountStr = "";
            moneyAmountStr = Txt3NormAmnt.Text;
            moneyAmountDoub = Convert.ToDouble(moneyAmountStr);
            if (moneyAmountDoub > 100.00)
            {                                                   // Get Yes or No answer
                Txt14ScrubYesNo.Text = "Yes";               
            }
            else
            {
                Txt14ScrubYesNo.Text = "No";
            }                                                   //
            #endregion

            Txt10ScrubFirstNam.Text = Txt4NormFirstNam.Text;
            Txt13ScrubItem.Text = Txt7NormItem.Text;
            Txt13ScrubItem.Text = Txt7NormItem.Text;
            Txt9ScrubAmt.Text = Txt3NormAmnt.Text;




        }
        else 
        {
            MessageBox.Show("Error: Information missing from the Data section");
        }
    }

    public void ScrubData()
    { // Begin Scrub Method

Upvotes: 0

Views: 582

Answers (2)

Tim
Tim

Reputation: 28520

There are a couple of things you need to do. First, you need to create class level variables (more properly referred to as fields) to hold information that needs to be accessed by different methods.

Secondly, you need to keep track of where you are (what line) in the file, because everytime you create a StreamReader, it will position the reader at the first line. As a corollary, as RogueBukkitDev said, you should read the file one time and dump it into a List<string> or an array (string[]). You would then increase or decrease the current position in the collection based on the user's direction - forward or back.

It could look something like this:

public partial class Form1 : Form
{ 

    // Class level fields
    private string fileName = String.Empty;
    private string[] fileLines;
    private int currentLine = 0;
    const char DELIM = '|';

    public void ScrubData()
    {           

        // Display an OpenFile Dialog box for user
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.Filter = "txt Files|*.txt";
        openFileDialog1.Title = "Select a txt File";

        // Show the Dialog. If user clicked OK in the dialog
        if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            try
            {
                fileName = openFileDialog1.FileName;
                newFileName = String.Format(@"{0}\{1}_scrubed.txt",
                           openFileDialog1.InitialDirectory,
                           Path.GetFileNameWithoutExtension(fileName));
                fileLines = File.ReadAllLines(fileName);
                currentLine = 0;
            } 
        }
    }

    public void BtnNext_Click(object sender, EventArgs e)
    {

        if (currentLine <= fileLines.Length)
        {
            string line2 = fileLines[currentLine];
            string[] word = line2.Split(DELIM);

            Txt2NormAccNum.Text = word[3];
            Txt3NormAmnt.Text = word[4];
            Txt4NormFirstNam.Text = word[1];
            Txt5NormLastNam.Text = word[2];
            Txt6NormSS.Text = word[0];
            Txt7NormItem.Text = word[5];

            currentLine = currentLine + 1;
        }
    }
}

Lots of changes here, and I ommitted code that wasn't relevant to the example.

First, I declare 4 fields - one for the fileName, one for the scrubbed filename, one for the current line of the file, and one constant for the delimiter.

Next, in the ScrubData method were the file is selected by the user, it simply calls File.ReadAllLines(), which will return an array of strings (one array element per line), and stores it in the class level field fileLines. It also sets the currentLine to 0, in case the user is choosing a different file before exiting the program.

In the btnNext_Click event handler, it reads the current line from the array of lines (fileLines) - after making sure you won't have an index out bounds error, then splits them on the delimiter and populates the text boxes. It then increases the currentLine by one.

To go back, it would be essentially the same logic, except that you would decrease currentLine by 1 (and check to make sure you don't go past 0).

This is the basic outline of what we've been trying to explain. You may need to modify it to suit your actual needs, but the principle remains the same.

Upvotes: 0

Rogue
Rogue

Reputation: 676

Of course it doesn't go from line to line. Each time the button is clicked you are simply reading the first line.

The best approach is to read all the lines in the file into a List<string> and have an int counter which you increment or decrement depending on if they move back or forward. Just increment/decrement each time and set the text to yourListVar[counter]

Or, if you want it to read from the file each time you can cycle through ReadLine()'s until you hit the index that matches the counter.

Upvotes: 1

Related Questions