Populating C# listview with context menu item
我想知道如何正确地使用"右键单击"上下文菜单中的选定预设项目中的信息来填充表单中的标签?我当前正在使用每个类\\'product \\'的\\'name \\'填充上下文菜单。然后,我想填写与用户右键菜单选择的项目相对应的标签。上下文菜单项将随着项目添加到列表而动态变化。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace rcMenu { public partial class Form1 : Form { public Form1() { InitializeComponent(); Product newProductA = new Product(); newProductA.Name ="Ice Cream"; newProductA.Category ="Dessert"; newProductA.Price ="Free"; productList.Add(newProductA); Product newProductB = new Product(); newProductB.Name ="Cherries"; newProductB.Category ="Produce"; newProductB.Price ="$10.00"; productList.Add(newProductB); Product newProductC = new Product(); newProductC.Name ="Soda"; newProductC.Category ="Beverage"; newProductC.Price ="$1.99"; productList.Add(newProductC); } public static List<Product> productList = new List<Product>(); public class Product { public String Name { get; set; } public String Category { get; set; } public String Price { get; set; } } private void SelectedPreset(object sender, EventArgs e) { label1.Text ="Product Name:" +"SELECTED"; label2.Text ="Product Category:" +"SELECTED"; label3.Text ="Product Price:" +"SELECTED"; } private void contextMenuStrip1_Opened(object sender, EventArgs e) { (contextMenuStrip1.Items[0] as ToolStripMenuItem).DropDownItems.Clear(); foreach (var p in productList) { var itemName = p.Name; (contextMenuStrip1.Items[0] as ToolStripMenuItem).DropDownItems.Add(itemName, null, SelectedPreset); } } } } |
首先订阅Opening事件,然后放置如下代码:
1 2 3 4 5 6 7 8 9 10 11 12 | private void contextMenuStrip1_Opening(object sender, CancelEventArgs e) { if(contextMenuStrip1.Items.Count > 0) contextMenuStrip1.Items.Clear(); foreach (var p in productList) { var itemName = p.Name; contextMenuStrip1.Items.Add(itemName); } e.Cancel = false; } |
下一步,订阅ItemClicked事件,并放置如下代码:
1 2 3 4 5 6 7 8 9 10 11 | private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { Product p = productList.Find(i => i.Name == e.ClickedItem.Text); //just in case its null... if(p != null) { label1.Text ="Product Name:" + p.Name; label2.Text ="Product Category:" + p.Category; label3.Text ="Product Price:" + p.Price; } } |
试试看!
1 2 3 4 5 6 7 | private void SelectedPreset(object sender, EventArgs e) { var p = productList.Where(x => x.Name == (sender as ToolStripMenuItem).Text).Single(); label2.Text ="Product Category:" + (sender as ToolStripMenuItem).Text; label3.Text ="Product Price:" + p.Price; } |
您必须完善一点,添加适当的验证