【问题标题】:Saving from a list box to a .csv file in c# Win Form在 c# Win Form 中从列表框保存到 .csv 文件
【发布时间】:2012-10-29 17:52:46
【问题描述】:

我一直在寻找如何做到这一点的几个小时,我认为最好的想法是为每个循环提供一个,然后将其传递给 Stream Writer。

我尝试了多种不同的方法,我想我可能只是不够好,无法看到我的错误,如果有人能够提供帮助,那就太好了。

当前文件已创建,我得到的唯一输出是第一行的“System.Windows.Forms.ListBox+ObjectCollection”,这表明我没有正确传递值。

代码如下:

        private void btnSave_Click(object sender, EventArgs e)
    {
        StreamWriter myOutputStream = new StreamWriter("Myfile.csv");
        myOutputStream.WriteLine(lstBox.Items);
        myOutputStream.Close();
        //foreach (object item in lstBox.Items)
        //string listString = lstBox.SelectedItem.ToString();
        //StreamWriter streamBox = File.CreateText(@"testfile.csv");
        //streamBox.Write(listString);
        //streamBox.Close();
        //if (SaveFileDialog.ShowDialog() == DialogResult.OK)
        //{
        //    System.IO.StreamWriter streamBox = new System.IO.StreamWriter(SaveFileDialog);
        //    foreach (object item in lstBox.Items)
        //        streamBox.WriteLine(item.ToString());
        //    streamBox.Close();
        //}
    }

所有注释掉的部分都是我过去尝试过的。但是现在,我认为最简单的方法是前三行。

感谢您的意见。

【问题讨论】:

    标签: c# file csv listbox


    【解决方案1】:

    您正在写出listBox.Items,这是一个ListBoxObjectCollection。您需要一个 foreach 循环来编写每个项目:

    StreamWriter myOutputStream = new StreamWriter("Myfile.csv");
    
    foreach (var item in lstBox.Items)
    {
        myOutputStream.WriteLine(item.ToString());
    }
    
    myOutputStream.Close();
    

    另请注意,您可以在此处使用using 块:

    using (StreamWriter myOutputStream = new StreamWriter("Myfile.csv"))
    {
        foreach (var item in lstBox.Items)
        {
            myOutputStream.WriteLine(item.ToString());
        }
    }
    

    【讨论】:

    • 非常感谢,效果很好。不知道为什么我看不到。
    【解决方案2】:

    首先,ListBox 中有什么内容?如果列表框中的项目只是字符串项目,那么您可以执行以下操作:

    StreamWriter myOutputStream = new StreamWriter("Myfile.csv");
    foreach (string item in lstBox.Items) {
        myOutputStream.WriteLine(item);
    }
    myOutputStream.Close();
    

    【讨论】:

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