简体   繁体   中英

C# Listbox convert text to hyperlink

I had a form that allow user to input the Name and perform search on various defined folders and display searched files (full path) in listbox. Now I want to covert the "Full Path" string into hyperlink so when user click on it inside the ListBox, it will launch Window explorer to locate and highlight the file. Here is the code I got so far:

 public void searchfile()
    {
        
        string fn = txt_filename.Text;
        lst_box1.Items.Clear();

        try
        {
            // Only get files that begin with the letter "c".
            List<string> dirs = new List<string>();
            dirs.AddRange(Directory.GetFiles(@"D:\Temp\Downloads", "*" + fn + "*"));
            
            foreach (string dir in dirs)
            {
                
                    lst_box1.Items.Add(dir);
                   
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

Thanks

Your question is about what to do within the visualization within WinForms. But your code is about how you fill the ListBox with data.

The ListBox has an event SelectedIndexChanged . This will be called, whenever another item was selected within that control.

You could subscribe to it and take the selected item value to open an explorer window at the desired location.

If you don't know, how to open a file explorer on a specific location with C#, take a look at this question .

You could also open it by double-clicking:

    private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        var item = listBox1.SelectedItem;

        // open Explorer with the path
        string sFolder_Path = listBox1.SelectedItem.ToString();
        Process.Start(sFolder_Path);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM