获取ListBox中所选项目的文本

10

我正在尝试在消息框中展示listBox1的选定项,以下是代码:

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

问题在于当我选择多个项目时,消息框仅显示我选择的第一个项目并重复该消息。例如:如果我选择了3个项目,则该消息将出现3次,每次都是第一个项目。

4个回答

15

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

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

7
在foreach循环中,i表示需要的索引。你正在使用listBox1.SelectedIndex,它只有第一个。因此,item应该是:
item = listBox1.Items[i].ToString ();

4
如何使用一个消息框来显示所有选定的项目?
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));

如果选择了任何选项,则应在您的消息框中为每个所选项目提供一行。可能有更漂亮的方法使用Linq来实现,但您没有指定.NET版本。

2
尝试这个解决方案:
string  item = "";    
foreach (int i in listBox1.SelectedIndices )
    {
       item += listBox1.Items[i] + Environment.NewLine;
    }
MessageBox.Show(item);

我喜欢这个答案,因为它让人们轻松地访问索引和值。 - Dave

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接