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

如何调整for循环实现将所有选中文件名存入List<string>集合?

问题原因

你当前代码的问题出在两点:

  • ListBox控件的SelectedItem属性在多选模式下仅会返回第一个被选中的项,即便你选中了多个元素,每次读取该属性拿到的都是同一个第一个选中项,最终只会重复添加第一个文件
  • 循环内的lstArquivosRetorno.SetSelected(i, true)逻辑会强制将所有项设置为选中状态,会覆盖用户原本的选中结果,若你的需求是收集用户手动勾选的文件,该行逻辑本身不符合需求
修复方案

场景1:收集用户手动选中的文件(推荐方案)

无需遍历所有项,直接遍历控件自带的SelectedItems已选中项集合即可:

// 若需要累加旧数据可删除以下清空语句
_relacaoArquivos.Clear();

foreach (var selectedItem in lstArquivosRetorno.SelectedItems)
{
    string nomeArquivo = string.Format(
      "{0}{1}", 
       Funcoes.IncludeBackSlash(edtPathArquivo.Text),
       selectedItem.ToString());

    _relacaoArquivos.Add(nomeArquivo);
}

场景2:需先全选所有项再全量收集

如果你的业务逻辑要求先全选所有列表项再收集所有文件名,修改取值逻辑为读取当前遍历下标的项即可:

// 若需要累加旧数据可删除以下清空语句
_relacaoArquivos.Clear();

for (int i = 0; i < lstArquivosRetorno.Items.Count; i++)
{
    lstArquivosRetorno.SetSelected(i, true);

    string nomeArquivo = string.Format(
      "{0}{1}", 
       Funcoes.IncludeBackSlash(edtPathArquivo.Text),
       lstArquivosRetorno.Items[i].ToString());

    _relacaoArquivos.Add(nomeArquivo);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 13:06:04