我正在构建一个 GUI 以使用列表框中的值更新数据库。我已经连接到服务器和数据库,并将信息放入正确的列中。我只是无法让它显示我选择的多个值。我对此很陌生。
string colors = "";
StringBuilder sb = new StringBuilder();
foreach (var items in listboxColor.SelectedItems)
{
sb.Append(listboxColor.SelectedItem + ", ");
}
colors = sb.ToString();
这是一个例子:
Example ListBox (** is the selected item)
**Red**
Blue
**Green**
Yellow
Orange
**Purple**
--------------------------
Output:
Red, Red, Red
我希望它是这样的:
Output:
Red, Green, Purple
谢谢!如果您需要更多信息,请告诉我。
最佳答案
其实“string.Join”要简单得多。
string.Join(", ", listboxColor.SelectedItems.Cast<object>())
由于逗号,使用“foreach”很复杂。
StringBuilder sb = new StringBuilder();
bool isFollowing = false;
foreach (var item in listboxColor.SelectedItems)
{
if (isFollowing)
{
sb.Append(", ");
}
else
{
isFollowing = true;
}
sb.Append(item);
}
string colors = sb.ToString();
关于C# - 在 ListBox 中选择多个项目并在 Windows 窗体中转换为逗号分隔的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37849462/