【问题标题】:How to send CheckedListBox selection into textfile?如何将 CheckedListBox 选择发送到文本文件中?
【发布时间】:2017-10-28 18:39:58
【问题描述】:

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

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

为简单起见,我先选择一首选定的歌曲。

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

出了什么问题?

【问题讨论】:

标签: c# winforms text-files streamwriter checkedlistbox


【解决方案1】:

遍历 CheckedItems 集合并收集字符串数组中的每个项目。我假设你用字符串填充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();

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多