C# 获取列表框中所选项目的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13614157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:10:56  来源:igfitidea点击:

Get text of selected items in a ListBox

c#winforms

提问by ?????? ??

I'm trying to show the selected items of listBox1 in a Message Box here's the code:

我正在尝试在消息框中显示 listBox1 的选定项目,这是代码:

int index;
string  item;
foreach (int i in listBox1 .SelectedIndices )
{
    index = listBox1.SelectedIndex;
    item = listBox1.Items[index].ToString ();
    groupids = item;
    MessageBox.Show(groupids);
}

The problem is that when I select more than one item the message box shows the frist one I've selected and repeats the message EX: if I selected 3 items the message will appear 3 times with the first item

问题是,当我选择多个项目时,消息框会显示我选择的第一个项目并重复消息 EX:如果我选择了 3 个项目,该消息将与第一个项目一起出现 3 次

采纳答案by System Down

The iin the foreach loop has the index you need. You're using listBox1.SelectedIndexwhich only has the first one. So item should be:

i在foreach循环中有你需要的指数。您正在使用listBox1.SelectedIndex它只有第一个。所以项目应该是:

item = listBox1.Items[i].ToString ();

回答by Jaime Torres

You can iterate through your items like so:

您可以像这样遍历您的项目:

        foreach (var item in listBox1.SelectedItems)
        {
            MessageBox.Show(item.ToString());
        }

回答by C-Pound Guru

How about 1 message box with all the selected items?

包含所有选定项目的 1 个消息框怎么样?

List<string> selectedList = new List<string>();
foreach (var item in listBox1.SelectedItems) {
   selectedList.Add(item.ToString());
}
if (selectedList.Count() == 0) { return; }
MessageBox.Show("Selected Items: " + Environment.NewLine +
        string.Join(Environment.NewLine, selectedList));

If any are selected, this should give you a line for each selected item in your message box. There's probably a prettier way to do this with linq but you didn't specify .NET version.

如果选择了任何一个,这应该为您的消息框中的每个选定项目提供一行。使用 linq 可能有一种更漂亮的方法来执行此操作,但您没有指定 .NET 版本。

回答by Kirill Kryazhnikov

Try this solution:

试试这个解决方案:

string  item = "";    
foreach (int i in listBox1.SelectedIndices )
    {
       item += listBox1.Items[i] + Environment.NewLine;
    }
MessageBox.Show(item);