使用C#中的ListBox选定项填充字符串数组

时间:2014-04-09 00:11:20

标签: c# arrays string winforms listbox

我有一个ListBox,其中X项(从9 - 90变化)的项目。我正在尝试填充(在按钮上单击)一个字符串数组,其中包含在ListBox中选择的项目。这是我到目前为止所拥有的

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选项的组合字符串。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:3)

使用ListBox.SelectedItems属性将所有选定项目放在一个字符串中,用换行符字符串分隔(您可以删除最后一个 for 循环,如以及其他一些代码)

您可以将所选项目的集合转换回它们的任何类型;在你的情况下,一个字符串。

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

答案 1 :(得分:0)

使用linq

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