C# ListView搜索问题求助:根据Amount值查找对应Value
解决C# ListView中根据第二列值查找对应第一列的问题
嘿,我来帮你搞定这个问题!你之前用Listview1.items.containskey("Amount5")没达到预期效果,是因为**ContainsKey()方法检查的是ListViewItem的Name属性,而不是子项(SubItems)里的内容**——你的Amount数据存在第二列的子项中,所以这个方法根本找不到目标内容。
下面给你两种实用的解决方案,都能实现你要的功能:
方法一:遍历所有项查找
这是最直观的方式,适合新手理解:
string targetAmount = "Amount5"; ListViewItem matchedItem = null; // 遍历ListView的每一项 foreach (ListViewItem item in listView1.Items) { // 检查第二列(SubItems[1],因为第一列是SubItems[0])的文本是否匹配 if (item.SubItems[1].Text.Equals(targetAmount, StringComparison.OrdinalIgnoreCase)) { matchedItem = item; break; // 找到就停止遍历,提升效率 } } // 根据结果执行操作 if (matchedItem != null) { // 存在的话,获取对应的Value(第一列文本) string correspondingValue = matchedItem.SubItems[0].Text; MessageBox.Show($"找到对应的值:{correspondingValue}"); // 这里可以把correspondingValue返回或者做其他处理 } else { MessageBox.Show("Not Found"); // 执行不存在时的操作 }
方法二:用LINQ简化查找(更简洁)
如果你熟悉LINQ,这种方式代码更紧凑,需要先引用System.Linq命名空间:
using System.Linq; // ... string targetAmount = "Amount5"; // 转换为可查询的集合,然后查找匹配项 var matchedItem = listView1.Items.Cast<ListViewItem>() .FirstOrDefault(item => item.SubItems[1].Text == targetAmount); if (matchedItem != null) { string correspondingValue = matchedItem.SubItems[0].Text; MessageBox.Show($"找到对应的值:{correspondingValue}"); } else { MessageBox.Show("Not Found"); }
额外提醒
- 确保你的ListView是Details模式(只有这种模式才会显示多列),否则SubItems可能无法正常访问。
- 如果你的Amount是数值类型(比如int、decimal),建议先把SubItems的文本转换成对应类型再比较,避免字符串匹配的误差(比如"100"和"100.0"的区别)。
- 如果需要忽略大小写匹配,可以用
StringComparison.OrdinalIgnoreCase参数,就像方法一里那样。
内容的提问来源于stack exchange,提问作者ArGOO
相关产品推荐
相关产品推荐

