You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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");
}

额外提醒

  1. 确保你的ListView是Details模式(只有这种模式才会显示多列),否则SubItems可能无法正常访问。
  2. 如果你的Amount是数值类型(比如int、decimal),建议先把SubItems的文本转换成对应类型再比较,避免字符串匹配的误差(比如"100"和"100.0"的区别)。
  3. 如果需要忽略大小写匹配,可以用StringComparison.OrdinalIgnoreCase参数,就像方法一里那样。

内容的提问来源于stack exchange,提问作者ArGOO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:25:44