Advertisement
Guest User

Untitled

a guest
Jan 12th, 2017
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. public partial class Form1 : Form
  2. {
  3. public Form1()
  4. {
  5. InitializeComponent();
  6. }
  7.  
  8. private void button1_Click(object sender, EventArgs e)
  9. {
  10. var button = sender as Button;
  11.  
  12. // create fake items list
  13. List<string> strings = new List<string>();
  14. for (int i = 0; i < 36; i++)
  15. strings.Add("ITEM " + (i+1));
  16. var listViewItems = strings.Select(x => new ListViewItem(x, 0)).ToArray();
  17.  
  18. // create a new list view
  19. ListView listView = new ListView();
  20. listView.View = View.SmallIcon;
  21. listView.SmallImageList = imageList1;
  22. listView.MultiSelect = false;
  23.  
  24. // add items to listview
  25. listView.Items.AddRange(listViewItems);
  26.  
  27. // calculate size of list from the listViewItems' height
  28. int itemToShow = 18;
  29. var lastItemToShow = listViewItems.Take(itemToShow).Last();
  30. int height = lastItemToShow.Bounds.Bottom + listView.Margin.Top;
  31. listView.Height = height;
  32.  
  33. // create a new popup and add the list view to it
  34. var popup = new ToolStripDropDown();
  35. popup.AutoSize = false;
  36. popup.Margin = Padding.Empty;
  37. popup.Padding = Padding.Empty;
  38. ToolStripControlHost host = new ToolStripControlHost(listView);
  39. host.Margin = Padding.Empty;
  40. host.Padding = Padding.Empty;
  41. host.AutoSize = false;
  42. host.Size = listView.Size;
  43. popup.Size = listView.Size;
  44. popup.Items.Add(host);
  45.  
  46. // show the popup
  47. popup.Show(this, button.Left, button.Bottom);
  48. }
  49. }
  50.  
  51. // change some properties (for selection) and subscribe the ItemActivate
  52. // event of the listView
  53. listView.HotTracking = true;
  54. listView.Activation = ItemActivation.OneClick;
  55. listView.ItemActivate += new EventHandler(listView_ItemActivate);
  56.  
  57.  
  58. // the click on the item invokes this method
  59. void listView_ItemActivate(object sender, EventArgs e)
  60. {
  61. var listview = sender as ListView;
  62. var item = listview.SelectedItems[0].ToString();
  63. var dropdown = listview.Parent as ToolStripDropDown;
  64. // unsubscribe the event (to avoid memory leaks)
  65. listview.SelectedIndexChanged -= listView_ItemActivate;
  66. // close the dropdown (if you want)
  67. dropdown.Close();
  68.  
  69. // do whatever you want with the item
  70. MessageBox.Show("Selected item is: " + item);
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement