![](/img/trans.png)
[英]c# - get multiple listbox values and turn into comma separated string winforms
[英]C# - Selecting multiple items in a ListBox and converting into a comma separated string in Windows Form
我正在構建一個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
謝謝! 如果您需要更多信息,請告訴我。
問題是foreach中的行。
您正在使用listboxColor.SelectedItem
獲取具有焦點的所選項目(因此始終相同)。
這是正確的代碼:
string colors = "";
StringBuilder sb = new StringBuilder();
foreach (var currentItem in lbOwner.SelectedItems)
{
sb.Append(currentItem + ", ");
}
colors = sb.ToString();
實際上,“ 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();
如果只有string
作為列表框項目,則可以執行此操作。
string colors = "";
StringBuilder sb = new StringBuilder();
foreach (string item in lbOwner.SelectedItems)
{
sb.Append(item + ", ");
}
colors = sb.ToString();
如果ListBoxItem
是對象,則需要將其ListBoxItem
為相應的類型並獲取所需的屬性/字段。
ex..
foreach (object item in lbOwner.SelectedItems)
{
sb.Append((item as type1).Prop1 + ", ");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.