Wouter
Wouter

Reputation: 575

C# List text files in a listbox and let user open them in a textbox

I'am pretty new to C# and I want a listbox with all text files in a folder and if the user dubbleclicks on the listed file the file will display in a textbox.

I don't want to use the openFileDialog function because the textfiles are on a webserver which I access using username:[email protected]/folder.

Kinda like a texteditor limited to edit only files in 1 folder :)
If this is possible using openFileDialog please tell me how.

I hope you can understand what I want to do.

Greetings,

Upvotes: 0

Views: 1777

Answers (1)

Nomad101
Nomad101

Reputation: 1698

From what I understand you are after, you want to iterate through the files in a specific directory and then allow them to be edited once opened with a double click in a listbox.

This can be done using the var Files = Directory.GetFiles("path", ".txt");

Files would be a string[] of the file names.

Then filling the Listbox with the files something like this:

ListBox lbx = new ListBox();
lbx.Size = new System.Drawing.Size(X,Y); //Set to desired Size.
lbx.Location = new System.Drawing.Point(X,Y); //Set to desired Location.
this.Controls.Add(listBox1); //Add to the window control list.
lbx.DoubleClick += OpenFileandBeginEditingDelegate;
lbx.BeginUpdate();
for(int i = 0; i < numfiles; i++)
  lbx.Items.Add(Files[i]);
lbx.EndUpdate();

Now your event delegate should look something like this:

OpenFileandBeginEditingDelegate(object sender, EventArgs e)
{
    string file = lbx.SelectedItem.ToString();
    FileStream fs = new FileStream(Path + file, FileMode.Open);

    //Now add this to the textbox 
    byte[] b = new byte[1024];
    UTF8Encoding temp = new UTF8Encoding(true);
    while (fs.Read(b,0,b.Length) > 0)
    {
        tbx.Text += temp.GetString(b);//tbx being the textbox you want to use as the editor.
    }
}

Now to add an event handler through the VS window editor click on the control in question and go to the properties pane for that control. You will need to then switch to the events pane and scroll untill you find the DoubleClick event if you use that the designer should auto-insert a valid delegate signature and allow you to write the logic for the event.

Upvotes: 2

Related Questions