将选定的列表框项目显示到消息框中
问题描述:
我可以将多个选定的项目从列表框中显示到按钮上的文本框中,但是如何在消息框中显示相同的内容?我的意思是在消息框中显示第一个项目不是问题,但同时有多个项目。建议请...将选定的列表框项目显示到消息框中
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace cities
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Clear();
foreach (object selectedItem in listBox1.SelectedItems)
{
textBox1.AppendText(selectedItem.ToString() + Environment.NewLine);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
答
您可以创建临时变量来保存文本,然后创建一个消息框。
StringBuilder message = new StringBuilder();
foreach (object selectedItem in listBox1.SelectedItems)
{
message.AppendLine(selectedItem.ToString());
}
MessageBox.Show(message.ToString());
答
在你点击按钮 -
textBox1.Clear();
string str = string.Empty;
foreach (object selectedItem in listBox1.SelectedItems)
{
str += selectedItem.ToString() + Environment.NewLine;
}
textBox1.Text = str;
MessageBox.Show(str);
+1
我想如果太多选择的项目,然后确定按钮,可能顶部酒吧将离开屏幕:) – Sayse 2013-02-26 08:48:12
答
您可以创建基于所有SelectedItems
一个字符串,然后显示在MessageBox。像
string str = string.Join(",",
listBox1.SelectedItems.Cast<object>().Select(r => r.ToString()));
MessageBox.Show(str);
真的很好的解决方案!谢谢! – 2013-02-26 08:58:39
你们真的很快好@Dmitry – Shrivallabh 2013-02-26 09:06:03