4

I am trying to make URL clickable inside of ListView item.

How do I do this?

The way I want it to work is to user store link in plain text, and then when I am retrieving the links I want to make them clickable in ListView.

This is how I retrieve entries from my database while read.GetString(2) pulls the URL value:

if (security.DecryptAES
    (read.GetString(1), storedAuth.Password, 
    storedAuth.UserName) == "Web Site Password")
{
    // Count Web passwords.
    countWeb++;
    Web = new ListViewItem("");
    Web.SubItems.Add(security.DecryptAES
        (read.GetString(2), storedAuth.Password, storedAuth.UserName));
    Web.SubItems.Add(security.DecryptAES
        (read.GetString(5), storedAuth.Password, storedAuth.UserName));
    Web.SubItems.Add(security.DecryptAES
        (read.GetString(6), storedAuth.Password, storedAuth.UserName));
    Web.Tag = read.GetInt32(0);
    lvWeb.Items.Add(Web);
}
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
HelpNeeder
  • 6,383
  • 24
  • 91
  • 155

1 Answers1

14

The first thing you want to do is give visual feedback to let the user know that the item is clickable. I'll just arbitrarily assume the url is in the 2nd column. Add the MouseMove event for the ListView:

    private void listView1_MouseMove(object sender, MouseEventArgs e) {
        var hit = listView1.HitTest(e.Location);
        if (hit.SubItem != null && hit.SubItem == hit.Item.SubItems[1]) listView1.Cursor = Cursors.Hand;
        else listView1.Cursor = Cursors.Default;
    }

The next step is very similar, implement the MouseUp event to detect a click on the sub-item:

    private void listView1_MouseUp(object sender, MouseEventArgs e) {
        var hit = listView1.HitTest(e.Location);
        if (hit.SubItem != null && hit.SubItem == hit.Item.SubItems[1]) {
            var url = new Uri(hit.SubItem.Text);
            // etc..
        }
    }
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • This seems very nice. So Uri is the object which creates URL? – HelpNeeder Dec 20 '11 at 01:10
  • Ok, I have used your code to hover hand over the field I wanted. But when I click nothing happens. Should that be a mouse click even instead? – HelpNeeder Dec 20 '11 at 01:32
  • 1
    Use the debugger. You are supposed to fill in the code where it says // etc.., just in case. – Hans Passant Dec 20 '11 at 01:48
  • Ah! Got ya, in this case I can add line: `System.Diagnostics.Process.Start(url.ToString());` and it works. All I need to work on on warning to open a site first. Thanks! – HelpNeeder Dec 20 '11 at 01:59