I'm writing a WPF application. How to Convert ListBox items to single string Value?
I have 1 Text Box, an ADD Button to add items to a List Box, and a SAVE Button to SAVE items in Console Window.
How can I do this?
//Concatenation of all items of list box
string allItems = string.Join(", ",listBox1.Items.OfType<object>());
//Concatenation of selected tiems of list box
string selectedItems= string.Join(", ",listBox1.SelectedItems.OfType<object>());
var listboxitems = listbox1.Items.Cast<ListBoxItem>().Select(p => p.Content as string);
string result= String.Join("|", listboxitems .ToArray());
This will place value1|value2|value3
On which ever Button Click you want to Convert that Items to single String value Add this piece of code :
Stringbuilder sb =new StringBuilder();
private void btn1_Click(object sender, RoutedEventArgs e)
{
//Suppose that ListBox name is listBox1
for(int i=0;listBox1.Items.Count; i++)
{
sb.Append(listBox1.Items[i].ToString());
}
}
use this Stringbuilder sb.ToString() to Your Text box
txtname.text =sb.ToString();
ListBox listBox1 = new ListBox();
for (int x = 1; x <= 5; x++)
{
listBox1.Items.Add("Item " + x.ToString());
}
StringBuilder sb = new StringBuilder();
foreach (var item in listBox1.Items)
{
sb.Append(item.ToString());
}
Console.WriteLine(sb.ToString());
您可以简单地尝试:
string[] listAsArray = listBoxPart.Items.OfType<string>().ToArray();
Add a new string content from your TextBox
:
Assume that you have a TextBox
name textBox
, You can get string
content of the textBox
by Text
property.
You have to create 2 Button
(s).
Button ADD: To add the
string
from yourTextBox
to yourListBox
Button SAVE: To save the
ListBox
items to a Console Window See the code:
ListBoxItem item1 = new ListBoxItem();
item1.Content = textBox.Text;
listBox.Items.Add(item1);
// Do the same with item2, item 3,... item n
Show in a Console Window:
foreach (var item in listBox.Items)
{
Console.WriteLine(item);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.