簡體   English   中英

C#中用ListBox選中項填充字符串數組

[英]Fill String Array With ListBox Selected Items in C#

我有一個列表框,其中包含 X 項(從 9 到 90 不等)的項目。 我試圖用在列表框中選擇的項目填充(單擊按鈕)一個字符串數組。 這是我到目前為止所擁有的

private void generateTam_Click(object sender, EventArgs e)
    {
        String sCombinedTam = "";
        String sTamResponseStart = "Dear $contacts.name.first,@\n@\nYour request has been received and completed.@\nThe following actions were taken:@\n";
        String sTamResponseEnd = "Thank you for choosing %company%, and have a great day!!@\n@\n$incidents.assigned.acct_id@\n%company%";

        sTamResponseStart = sTamResponseStart.Replace("@\n", System.Environment.NewLine); //Replaces token @\n with NewLine
        //Gets Actions Selected, Sends to Array
        String[] sActionItemsSelected = new String[actionsListBox.Items.Count];
        for (int x = 0; x < actionsListBox.Items.Count; ++x)
        {
            if (actionsListBox.GetSelected(x) == true)
            {
                actionsListBox.Items.CopyTo(sActionItemsSelected, 0);

            }
        }
        //Gets Profiles Selected, Sends to Array
        String[] sProfileItemsSelected = new String[profilesListBox.Items.Count];
        for (int x = 0; x < profilesListBox.Items.Count; ++x)
        {
            if (profilesListBox.GetSelected(x) == true)
            {
                profilesListBox.Items.CopyTo(sProfileItemsSelected, x);
            }
            else if (profilesListBox.GetSelected(x) == false)
            {
                sProfileItemsSelected[x] = "";
            }
        }
        //Combines strings for end response
        for (int i = 0; i < sActionItemsSelected.Length; ++i)
        {
            sCombinedTam = sCombinedTam + sActionItemsSelected[i] + "@\n";
        }
        sCombinedTam = sCombinedTam.Replace("@\n", System.Environment.NewLine);
        sTamResponseEnd = sTamResponseEnd.Replace("@\n", System.Environment.NewLine);
        sCombinedTam = sTamResponseStart + sCombinedTam + sTamResponseEnd;
        notesTextBox.Text = sCombinedTam;

        //Outputs ENTIRE index ListBoxes not just selected items.

    }

問題出現在最后,不是將notesTextBox.Text設置為僅包含 ListBox Selected Items 的組合字符串,而是將其設置為包含 EVERY ListBox 選項的組合字符串。

任何幫助將不勝感激。

使用ListBox.SelectedItems屬性可在單個字符串中獲取所有選定項,並用換行符分隔(可以刪除最后一個 for 循環以及其他一些代碼)

您可以將所選項目的集合轉換回它們的類型。 就您而言,是一個字符串。

var selectedItems =
    String.Join(Environment.NewLine, listBox1.SelectedItems.Cast<string>());

使用LINQ

items = (from string s in listBox1.SelectedItems select s).ToArray();

這對我有用:

Dim selectedItems As String() = listBox1.SelectedItems.Cast(Of String).ToArray

暫無
暫無

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

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