Search code examples
c#listdirectoryreadfileclickable

C# Making a clickable list with names from a specific folder


Ive searched high and low for this but cant find it.

Im trying to make a list with names from a specific folder that holds a lot of text files. I want the list to be clickable so let's say if it show a name like "Name1" and i click it i want it to get me to a new form with a textbox showing the information from the textfile "Name1".

I hope ive explained my problem well enough so someone can help me and ill be very grateful for any help i can get!


Solution

  • This is not a code write-my-code site, so I will only give you hints:

    • Since you want to display text in a second form, add a second form to your project
    • Since we want to work with files and folders, add the System.IO namespace to both forms
    • Since we want to tell the second form about the name of the file it will display, change its constructor to something like this:

        string fileName;
        public Form2(string fn)
        {
            InitializeComponent();
            fileName = fn;
    
        }
    
    • Since you want to display a list, add a ListBox to the 1st Form
    • Since you want to display a text, add a TextBox to the 2nd Form
    • To get a list of filenames use Directory.GetFiles()
    • To add the result to the Items of the ListBox use ListBox.AddRange() method
    • To access the clicked one use ListBox.SelectedItem in the ListBox.SelectedIndexChanged event
    • Before using it check if there is a selection: if (listBox1.SelectedItems.Count > 0)..
    • Use ToString() on the Item
    • Create a new Form2(filename) and Show() it
    • There, use File.ReadAllText and assign the result to textBox1.Text

    Please look up all the methods on MSDN to find the right format and examples of their use!