0

Hey I am currently stuck. I have the following code that takes a line from a file, based on specific string and returns it, then it can be edited, and applied back to a textbox that contains the file content into the line that the string was initially taken from.

    private void citationChange()
    {
        List<string> matchedList = new List<string>();

        string[] linesArr = File.ReadAllLines(fileName);

        //find matches
        for (int a = 0; a < linesArr.Length; a++)
        {
            string s = linesArr[a];
            if (s.Contains(citation))
            {
                matchedList.Add(linesArr[a]); //matched
                lineBeingEdited = a;
                break; //breaks the loop when a match is found
            }
        }

        //output
        foreach (string s in matchedList)
        {
            string citationLine = s;
            string[] lineData = citationLine.Split(',');
            editModuleComboBox.Text = lineData[1];
            selectedModuleLabel.Text = lineData[2];
            moduleTitleTextBox.Text = lineData[3];
            creditsTextBox.Text = lineData[4];
            semesterTextBox.Text = lineData[5];
            examWeightingTextBox.Text = lineData[6];
            examMarkTextBox.Text = lineData[7];
            testWeightingTextBox.Text = lineData[8];
            testMarkTextBox.Text = lineData[9];
            courseworkWeightingTextBox.Text = lineData[10];
            courseworkMarkTexbox.Text = lineData[11];
        }
    }

How can I recreate/change this code but for it to read a textbox instead of a file?

Thanks

Dr4ken
  • 27
  • 1
  • 11

2 Answers2

2

Change this:

string[] linesArr = File.ReadAllLines(fileName);

to:

string[] linesArr = theTextBox.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
ainwood
  • 992
  • 7
  • 17
1

When reading your file File.ReadAllLines basically splits the entire text by \r\n. So you could do this with your text from the textbox:

exchange this line:

string[] linesArr = File.ReadAllLines(fileName);

to this:

string[] linesArr = YourTextBox.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);

or this:

string[] linesArr = YourTextBox.Text.Split(new char[] {'\r', '\n'});
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
  • 1
    That will give an error, `Argument 1: cannot convert from 'string' to 'char'` – ainwood Aug 17 '17 at 09:44
  • There is a chance that the final string and the original may not be 100% the same. https://msdn.microsoft.com/en-us/library/s2tte0y1(v=vs.110).aspx `A line is defined as a sequence of characters followed by a carriage return ('\r'), a line feed ('\n'), or a carriage return immediately followed by a line feed. The resulting string does not contain the terminating carriage return and/or line feed.` – mjwills Aug 17 '17 at 10:22