C#Newbie01

I have been trying to figure out how to do this, and have found some interesting articles, but have had no luck whatsoever, so I figured I would post. I have a listBox, which is populated with all of the files in a specified folder. I would like to, when I click on one of the files for it to open with the appropriate application so that I can view it. I haven't been able to get anything to happen though, so I hope someone can help me.

Thank you very much.


Re: Visual C# Express Edition Open File in listBox on click?

Timo S

// If listBox has full path of the file, you can open it by starting a new process.
System.Diagnostics.Process.Start(listBox1.SelectedItem.ToString());


Regards,
Timo Salomaki





Re: Visual C# Express Edition Open File in listBox on click?

jrboddie

1. In the designer, double click the listBox creating an event handler for SelectedIndexChanged.

2. Add two lines to the event handler like this:

Code Snippet

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)

{

string file = listBox1.SelectedItem.ToString();

System.Diagnostics.Process.Start(file);

}

(This assumes your listbox is named 'listBox1'.

3. Run program





Re: Visual C# Express Edition Open File in listBox on click?

Timo S

Looks like I was a little bit faster than jrboddie...





Re: Visual C# Express Edition Open File in listBox on click?

C#Newbie01

Wow, by less than a second... lol...

Thank you both very much for your help, I will try this today and if all goes well mark this thread as answered. I will post back if I have any problems.

Thank you very much.






Re: Visual C# Express Edition Open File in listBox on click?

Timo S

There's also File.Open() method in System.IO namespace. You may want to try it too and figure out which one of this suggestions is better.


Timo Salomaki





Re: Visual C# Express Edition Open File in listBox on click?

C#Newbie01

Thank you very much everyone for all of your help. This helped me out tremendously. The item I have being added to the listBox was only the file name, not the entire location, etc. (So as to make it clearer), so I made a couple of changes so that I could do that. For the purpose of helping anyone else that might want to open a file this way, here is how I was able to do it:

Code Snippet

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
string dir = Environment.CurrentDirectory + @"\Files\MyFiles\";
string file = listBox1.SelectedItem.ToString();

System.Diagnostics.Process.Start(dir + file);
}
catch
{
MessageBox.Show("Error Loading File." + Environment.NewLine + "File Not Found.", "Error",
MessageBoxButtons.OK);
}
}




Thank you all again for all of your help.




Re: Visual C# Express Edition Open File in listBox on click?

Timo S

You're welcome! Smile