C# 将选定值添加到字符串

C# 将选定值添加到字符串,c#,asp.net,loops,foreach,C#,Asp.net,Loops,Foreach,考虑以下代码: foreach (ListItem item in lstViolations.Items) { if (item.Selected) { messageBody += item.Value + Environment.NewLine; } } 我正在尝试遍历lst中的每个ListItem。但是,只有第一个选择的值被添加到messageBody,我不明白这是为什么 另外,添加messageBody+=“test”仅打印第一个列表项,后面跟

考虑以下代码:

foreach (ListItem item in lstViolations.Items)
{
    if (item.Selected)
    {
        messageBody += item.Value + Environment.NewLine;
    }
}
我正在尝试遍历
lst
中的每个
ListItem
。但是,只有第一个选择的值被添加到
messageBody
,我不明白这是为什么

另外,添加
messageBody+=“test”
仅打印第一个列表项,后面跟着
test

尝试以下操作: 如果是ListView,则:

foreach(ListViewItem Item in lstViolations.SelectedItems)
       messageBody+= Item.Text + Environment.NewLine;
如果是列表框,则:

foreach(string Item in lstViolations.SelectedItems)
       messageBody+= Item + Environment.NewLine;
这将仅迭代选定的项目


编辑:没有查看标签。这对ASP.NET不起作用

甚至更干净更容易

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

是否在列表框上启用了多项选择
SelectionMode=Multiple“
跟踪它。测试是否多次返回真值?…感谢Icarus。这是漫长的一天。+1用于使用Environment.NewLine这似乎不是一个有效的选项。没有
SelectedItems
属性(-1)。您可能希望看到这一点:如果您正在使用列表中的任何一个,则上述操作都可以。@DelegateX:标记为这是ASP.NET而不是Winforms,不是ListView。ASP.NET中不存在类似于
SelectedItems
的内容。同样,ASP.NET中也不存在此类内容。ok..messageBody=string.Join(Environment.NewLine,lstViolations.Items.Where(i=>i.Selected.Select)(i=>i.Value))