locked
how to control lines of text displayed in Rich Text Box using C# RRS feed

  • Question

  • Hello Guru's

    i have a small application which contains 2 controls: List box and rich text box.

    List box holds file names, rich text box holds lines for all files in a list box.

    I want Rich Text Box to show lines starting with the line selected in list box. 

    If i click 2nd line, Rich Box start showing lines starting for 2nd file and so on.

    Can you please recommend how to do it.


    gene

    • Moved by CoolDadTx Monday, September 21, 2015 3:23 PM Winforms related
    Sunday, September 20, 2015 11:16 PM

Answers

  • Hi,

    Sorry, but I'm still confused on what really your requirement is.:) But based on my understanding is that you want to load all your files and its contents to a listview and rich textbox which consists of 3 files with 500 lines per file for its content, for a total of 1500 lines will be display to a rich textbox initially. If the user choose file1 at the listview then displays all the contents of files from file1 to file3. And if the user choose file2 then displays only file2 and file3. And if the user choose file3 then display only file3 and so on.

    I hope that I'm correct with my guess.:)

    So I just made a modification of the code that I had previously posted, to match up my understanding to your problem.

    private void Form1_Load(object sender, EventArgs e)
            {
                //initialize listview
                listView1.View = View.Details;
                listView1.Columns.Add("FileName", 150, HorizontalAlignment.Left);
                listView1.Columns.Add("Path", 250, HorizontalAlignment.Left);
                listView1.SelectedIndexChanged += new EventHandler(listView1_SelectedIndexChanged);
    
                //load all files and its contents to a listview and rich textbox.
                populateFilesToListview();
                loadSelectedIndexes(0); //set the index to 0 to load all files to the textbox.
            }
    
            private void populateFilesToListview()
            {
                string textFileDirectory = @"D:\Text Files", //Assuming that the contents of the folder are all text files. Change this folder name.
                    fileName, pathName;
                listView1.Items.Clear();
                string[] files = Directory.GetFiles(textFileDirectory); //get all files in a directory.
                foreach (var file in files)
                {
                    fileName = Path.GetFileNameWithoutExtension(file); //get only the filename.
                    pathName = Path.GetFullPath(file); //get the path and the file name
                    ListViewItem item = new ListViewItem(fileName); //sending filename to the filename column of a listview.
                    item.SubItems.Add(pathName); //sending full path name to the next column (Path) of a listview.
                    listView1.Items.Add(item); //populate listview.
                }
            }
    
            //handle selectedindexchange event to fire the file selection.
            private void listView1_SelectedIndexChanged(object sender, EventArgs e)
            {
                if (listView1.SelectedItems.Count > 0)
                {
                    loadSelectedIndexes(listView1.Items.IndexOf(listView1.SelectedItems[0]));
                }
            }
    
            private void loadSelectedIndexes(int index)
            {
                //reset the content of rich text box
                richTextBox1.Text = ""; 
                //get the current index of the selected file.
                for (int i = index; i < listView1.Items.Count; i++)
                {
                    //load selected files to textboxes.
                    loadFilesToTextbox(listView1.Items[i].SubItems[1].Text);
                }
            }
            
            private void loadFilesToTextbox(string path)
            {
                //strFile.LoadFile(path, RichTextBoxStreamType.PlainText);
                string text = System.IO.File.ReadAllText(path);
                //finally set to your richtextbox
                richTextBox1.Text = String.Format("{0}", (!String.IsNullOrEmpty(richTextBox1.Text)) ? richTextBox1.Text + "\n" : "") + text;
            }


    • Edited by Hardz Tarrayo Tuesday, September 22, 2015 1:48 AM
    • Proposed as answer by Youjun Tang Friday, September 25, 2015 9:00 AM
    • Marked as answer by Youjun Tang Tuesday, September 29, 2015 1:52 AM
    Tuesday, September 22, 2015 1:47 AM
  • If your files have exactly 500 lines, then use the value of ListBox.SelectedIndex, multiply it with 500, then pass to RichTextBox.GetFirstCharIndexFromLine. Then assign the value to RichTextBox.SelectionStart. Also set SelectionLength to zero.

    If the files have different number of lines (or as an alternative to previous approach), after appending the next file keep the current RichTextBox.TextLength value (or better SelectionStart after moving the caret to the end) in some collection or object associated with your listbox items. Later assign the kept value to RichTextBox.SelectionStart.


    • Edited by Viorel_MVP Tuesday, September 22, 2015 6:08 AM
    • Proposed as answer by Youjun Tang Friday, September 25, 2015 9:00 AM
    • Marked as answer by Youjun Tang Tuesday, September 29, 2015 1:52 AM
    Tuesday, September 22, 2015 6:04 AM

All replies

  • Hi,

    If my understanding is correct, try this code:

    private void Form1_Load(object sender, EventArgs e) { //initialize listview listView1.View = View.Details; listView1.Columns.Add("FileName", 150, HorizontalAlignment.Left); listView1.Columns.Add("Path", 250, HorizontalAlignment.Left); } //handle button click event to populate the files to the listview private void button1_Click(object sender, EventArgs e) { populateFilesToListview(); } private void populateFilesToListview() { /*FolderBrowserDialog folder = new FolderBrowserDialog(); //folder.Description = "Custom Description"; if (folder.ShowDialog() == DialogResult.OK) { listView1.Items.Clear(); string[] files = Directory.GetFiles(folder.SelectedPath); foreach (string file in files) { string fileName = Path.GetFileNameWithoutExtension(file), pathName = Path.GetFullPath(file); ListViewItem item = new ListViewItem(fileName); item.SubItems.Add(pathName); listView1.Items.Add(item); } }*/ //or string textFileDirectory = @"Your folder Location, ex: D:\Text Files", //Assuming that the contents of the folder are all text files. Change this folder name. fileName, pathName; listView1.Items.Clear(); string[] files = Directory.GetFiles(textFileDirectory); //get all files in a directory. foreach (var file in files) { fileName = Path.GetFileNameWithoutExtension(file); //get only the filename. pathName = Path.GetFullPath(file); //get the path and the file name ListViewItem item = new ListViewItem(fileName); //sending filename to the filename column of a listview. item.SubItems.Add(pathName); //sending full path name to the next column (Path) of a listview. listView1.Items.Add(item); //populate listview. } } //handle selectedindexchange event to fire the file selection. private void listView1_SelectedIndexChanged(object sender, EventArgs e) { if (listView1.SelectedItems.Count > 0) { //get the current index of the selected file. int index = listView1.Items.IndexOf(listView1.SelectedItems[0]); for (int i = index; i < listView1.Items.Count; i++) { //load selected files to textboxes. loadFilesToTextbox(listView1.Items[i].SubItems[1].Text); } } } private void loadFilesToTextbox(string path) { //temporarily set the txt file to a string.

    string text = System.IO.File.ReadAllText(path); //finally set to your richtextbox richTextBox1.Text = String.Format("{0}", (!String.IsNullOrEmpty(richTextBox1.Text)) ? richTextBox1.Text + "\n" : "") + text; }


    Hope it helps.


    Monday, September 21, 2015 5:28 AM
  • Right click on your ListBox and click actions. 

    Double click on and add this code. 

    Everytime you selection changes on your listbox, the selected file (if exists) will be shown in your richtextbox. 

     private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
            {
                var fileName = listBox1.SelectedItem.ToString();
                if(File.Exists(fileName))
                {
                    var text = File.ReadAllText(fileName);
                    richTextBox1.Text = text;
                }
            }

    Monday, September 21, 2015 6:28 AM
  • "I want Rich Text Box to show lines starting with the line selected in list box."

    Then you ListBox contains the lines and not the file names as you posted. Please clarify this

    Also I'm not sure why did you use the RichTextBox and not the normal TextBox with multiline enabled for this. Otherwise if you're handling format you must use .Rtf property instead of .Text.


    Fouad Roumieh

    Monday, September 21, 2015 9:05 AM
  • hello everybody who responded on my inquiry, I really appreciate that.

    I need to clarify my task.

    For instance, I have 3 entries / lines in left ListBox: 'file1', 'file2', 'file3'.

    Each file have 500 lines. 3 file lines are already being loaded into RichTextBox on the right. So RT2 holds 1500 lines of combined rows.

    When I click on LB1 2nd entry, I want to see RT box scrolls to the first line of file2 and display start showing file2 lines. At that time, RT2 entries generally do not change. I can still scroll them back and force to browse 1500 lines of data. But if I click file entry in LB1, the position of rows displayed in RT2 is reset to show starting from that file.


    gene

    Monday, September 21, 2015 3:41 PM
  • Hi,

    Sorry, but I'm still confused on what really your requirement is.:) But based on my understanding is that you want to load all your files and its contents to a listview and rich textbox which consists of 3 files with 500 lines per file for its content, for a total of 1500 lines will be display to a rich textbox initially. If the user choose file1 at the listview then displays all the contents of files from file1 to file3. And if the user choose file2 then displays only file2 and file3. And if the user choose file3 then display only file3 and so on.

    I hope that I'm correct with my guess.:)

    So I just made a modification of the code that I had previously posted, to match up my understanding to your problem.

    private void Form1_Load(object sender, EventArgs e)
            {
                //initialize listview
                listView1.View = View.Details;
                listView1.Columns.Add("FileName", 150, HorizontalAlignment.Left);
                listView1.Columns.Add("Path", 250, HorizontalAlignment.Left);
                listView1.SelectedIndexChanged += new EventHandler(listView1_SelectedIndexChanged);
    
                //load all files and its contents to a listview and rich textbox.
                populateFilesToListview();
                loadSelectedIndexes(0); //set the index to 0 to load all files to the textbox.
            }
    
            private void populateFilesToListview()
            {
                string textFileDirectory = @"D:\Text Files", //Assuming that the contents of the folder are all text files. Change this folder name.
                    fileName, pathName;
                listView1.Items.Clear();
                string[] files = Directory.GetFiles(textFileDirectory); //get all files in a directory.
                foreach (var file in files)
                {
                    fileName = Path.GetFileNameWithoutExtension(file); //get only the filename.
                    pathName = Path.GetFullPath(file); //get the path and the file name
                    ListViewItem item = new ListViewItem(fileName); //sending filename to the filename column of a listview.
                    item.SubItems.Add(pathName); //sending full path name to the next column (Path) of a listview.
                    listView1.Items.Add(item); //populate listview.
                }
            }
    
            //handle selectedindexchange event to fire the file selection.
            private void listView1_SelectedIndexChanged(object sender, EventArgs e)
            {
                if (listView1.SelectedItems.Count > 0)
                {
                    loadSelectedIndexes(listView1.Items.IndexOf(listView1.SelectedItems[0]));
                }
            }
    
            private void loadSelectedIndexes(int index)
            {
                //reset the content of rich text box
                richTextBox1.Text = ""; 
                //get the current index of the selected file.
                for (int i = index; i < listView1.Items.Count; i++)
                {
                    //load selected files to textboxes.
                    loadFilesToTextbox(listView1.Items[i].SubItems[1].Text);
                }
            }
            
            private void loadFilesToTextbox(string path)
            {
                //strFile.LoadFile(path, RichTextBoxStreamType.PlainText);
                string text = System.IO.File.ReadAllText(path);
                //finally set to your richtextbox
                richTextBox1.Text = String.Format("{0}", (!String.IsNullOrEmpty(richTextBox1.Text)) ? richTextBox1.Text + "\n" : "") + text;
            }


    • Edited by Hardz Tarrayo Tuesday, September 22, 2015 1:48 AM
    • Proposed as answer by Youjun Tang Friday, September 25, 2015 9:00 AM
    • Marked as answer by Youjun Tang Tuesday, September 29, 2015 1:52 AM
    Tuesday, September 22, 2015 1:47 AM
  • If your files have exactly 500 lines, then use the value of ListBox.SelectedIndex, multiply it with 500, then pass to RichTextBox.GetFirstCharIndexFromLine. Then assign the value to RichTextBox.SelectionStart. Also set SelectionLength to zero.

    If the files have different number of lines (or as an alternative to previous approach), after appending the next file keep the current RichTextBox.TextLength value (or better SelectionStart after moving the caret to the end) in some collection or object associated with your listbox items. Later assign the kept value to RichTextBox.SelectionStart.


    • Edited by Viorel_MVP Tuesday, September 22, 2015 6:08 AM
    • Proposed as answer by Youjun Tang Friday, September 25, 2015 9:00 AM
    • Marked as answer by Youjun Tang Tuesday, September 29, 2015 1:52 AM
    Tuesday, September 22, 2015 6:04 AM
  • Hello All, thank you for responds.

    Actually I was looking for on how to move insertion point in richtextbox.

    I found it just to see another problem:

                    RT2.SelectionStart = i1;
                    RT2.ScrollToCaret();

    However, it does not work as intended. 

    My display is off after I set number of characters to RT2.

    Here is what I do:

    1. Populate (add entry ) to ListBox LB1 with file name string.

    2. Populate list mylist with the content of the file: 

    myList.Add(s2);

    3. Populate assoc. array D3 with the file name and running subtotal of characters, so each entry consist of: file name + character counter to be used later in SelectionStart.

    4. Once LB1 and myList are populated, I do equalize RT2 with myList :

    RT2.Lines = myList.ToArray()

    Then, if I want to set RT2 visible region to the content of file2 of LB1, I execute:

                    RT2.SelectionStart = i1;
                    RT2.ScrollToCaret();

    But it simply does not move insertion point to correct position. In one instance it's almost 1000 characters off. I cut and paste RT2 text to text file and run character count (wc -c).

    Can anybody see flaw in this processing?


    gene

    Tuesday, September 29, 2015 4:09 AM