簡體   English   中英

C#WPF ListBox轉換為字符串

[英]C# WPF ListBox to string

如何將ListBox內容傳遞給字符串(字符串數組?)。 我需要獲取類似的數據格式:

Value1
Value2
Value3

其中每個值是一個單獨的ListBox項。

編輯:我對我的問題不太准確。 我想通過WPF應用程序通過電子郵件發送所需的值列表,不幸的是,值在一行中發送。 甚至使用/ n也無濟於事。 我該怎么做才能將外觀更改為列表而不是字符串?

public string[] get()
{
    string[] arr = new string[listBox1.Items.Count];
    for (int i = 0; i < listBox1.Items.Count; i++)
    {
        arr[i] = listBox1.Items[i].ToString();
    }
    return arr;
}

簡單的一線解決方案:

List<string> items = ListBox1.Items.Cast<ListBoxItem>().Select(p=> p.Content as string).ToList();

您可以使用單個字符串值而不是數組來存儲結果,如下所示:

string emailData=string.Empty;
//get each item's text & append emailData.
foreach(var item in listBox1.Items)
 {
     string itemData=((ContentControl)item).Content.ToString();
     emailData = emailData +itemData+"\n";
 }
//Call the method that writes the data to email, remember to use Trim() while using emailData.
WriteToEmail(emailData.Trim());
//lb is the Listbox; array is a string[]
lb.ItemsSource= array;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM