【问题标题】:Adding selected values to a string将选定的值添加到字符串
【发布时间】:2012-08-13 19:08:49
【问题描述】:

考虑这段代码:

foreach (ListItem item in lstViolations.Items)
{
    if (item.Selected)
    {
        messageBody += item.Value + Environment.NewLine;
    }
}

我正在尝试遍历lstViolations 中的每个ListItem。但是,只有第一个选定的值被添加到 messageBody,我不知道为什么会这样。

此外,添加messageBody += "test" 仅打印第一个列表项,后跟test

【问题讨论】:

  • 您是否在列表框上启用了多选? SelectionMode=Multiple"
  • 追踪它。测试是否多次返回 true?
  • ...谢谢伊卡洛斯。这是漫长的一天。
  • +1 使用 Environment.NewLine

标签: c# asp.net loops foreach


【解决方案1】:

试试这个: 如果是ListView,那么:

foreach(ListViewItem Item in lstViolations.SelectedItems)
       messageBody+= Item.Text + Environment.NewLine;

如果是Listbox,那么:

foreach(string Item in lstViolations.SelectedItems)
       messageBody+= Item + Environment.NewLine;

这将仅遍历选定的项目。

编辑:没有查看标签。这不适用于 ASP.NET!

【讨论】:

【解决方案2】:

甚至更清洁、更容易。

messageBody = string.Join(Environment.NewLine, lstViolations.SelectedItems);

【讨论】:

  • 这里也一样,这种东西在ASP.NET中是没有的。
  • ok.. messageBody = string.Join(Environment.NewLine, lstViolations.Items.Where(i => i.Selected).Select(i => i.Value))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-15
  • 2022-01-23
  • 1970-01-01
  • 2018-07-27
相关资源
最近更新 更多