如何将CheckedListBox选择发送到文本文件?

时间:2017-05-28 09:34:17

标签: c# winforms text-files streamwriter checkedlistbox

我第一次尝试自己编码,并决定在Winforms上制作音乐播放器。

我有一个CheckedListBox,它已经填充了文件夹中歌曲的名称。 当我点击一个按钮时,它应该在关闭表单之前将我选中的歌曲的名称发送到.txt文件中以便进一步操作。

为简化起见,我先选择1首选定的歌曲。

private void selectbtn_Click(object sender, EventArgs e)
{
    selectedSongs = checkedListBox1.CheckedItems.ToString();
    songRecord.writeRecord(selectedSongs); //i initialised my streamreader/streamwriter class and called it songRecord
    this.Close();   
}

在我的streamreader/writer课程中,这就是我所拥有的

class DataRecord
{
    public void writeRecord(string line)
    {
        StreamWriter sw = null;
        try
        {
            sw = new StreamWriter(@"C:\Users\Me\Desktop\JAM_MACHINE\record.txt", true);
            sw.WriteLine(line);
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("Error: File not found.");
        }
        catch (IOException)
        {
            Console.WriteLine("Error: IO");
        }
        catch(Exception)
        {
            throw;
        }
        finally
        {
            if (sw != null)
                sw.Close();
        }
    }

    public void readRecord()
    {
        StreamReader sr = null;
        string myInputline;
        try
        {
            sr = new StreamReader(@"C:\Users\Me\Desktop\JAM_MACHINE\record.txt");
            while ((myInputline = sr.ReadLine()) != null) ; //readline reads whole line
            Console.WriteLine(myInputline);
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("Error: File not found");
        }
        catch(IOException)
        {
            Console.WriteLine("Error: IO");
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            if (sr != null)
                sr.Close();
        }
    }
}

当我运行它时,.txt文件不会显示我的选择。它只显示: System.Windows.Forms.CheckedListBox+CheckedItemCollection

出了什么问题?

1 个答案:

答案 0 :(得分:1)

遍历CheckedItems Collection并收集字符串数组中的每个项目。我假设您使用字符串

填充checkedListBox
   private void selectbtn_Click(object sender, EventArgs e)
    {


        string[] checkedtitles = new string[checkedListBox1.CheckedItems.Count];
        for (int ii = 0; ii < checkedListBox1.CheckedItems.Count; ii++)
        {
            checkedtitles[ii] = checkedListBox1.CheckedItems[ii].ToString();
        }
        string selectedSongs = String.Join(Environment.NewLine, checkedtitles);

        songRecord.writeRecord(selectedSongs);
        this.Close();

    }
相关问题