saving data from a query as a csv file

删除回忆录丶 提交于 2020-01-04 02:49:09

问题


I've got an application which opens a csv file and displays all the contents into a formatted datagridview. From there I have a button which opens another form that contains a series of checkboxes. The check boxes have all the attributes of the csv file we opened before, and the user is supposed to be able to query the file based on witch attributes they want, then save the file.

For example, if they only want a file which displays all the entries for animals with wings, they select the wings check box only. From there, you select the save button and it's supposed to save the file.

private void button1_Click(object sender, EventArgs e)
{
    SaveFileDialog saveFileDialog1 = new SaveFileDialog();
    const string filter = "CSV file (*.csv)|*.csv| All Files (*.*)|*.*";
    const string header = "Animal_Name,Hair,Feathers,Eggs,Milk,Airborne,Aquatic,Predator,Toothed,Backbone,Breathes,Venomous,Fins,Legs,Tail,Domestic,Catsize,Type";
    StreamWriter writer = null;

    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
    {        
        filter = saveFileDialog1.FileName;
        writer = new StreamWriter(filter);

        writer.WriteLine(header);
        foreach (Animal animal in animalQuery)
        {
            writer.Write(animal);
        }  
        writer.Close();
    }
}

This is the code for the save button, but there are errors under:

filter = saveFileDialog1.FileName;
writer = new StreamWriter(filter); 

I'm not sure why.


回答1:


unless your code is exact, you cannot assign to a constant variable for your code saying:

filter = saveFileDialog1.FileName;

You declared "filter" as a constant variable further up:

const string filter = "CSV file (.csv)|.csv| All Files (.)|.";

Try that:

        SaveFileDialog saveFileDialog1 = new SaveFileDialog();
        string filter = "CSV file (*.csv)|*.csv| All Files (*.*)|*.*";
        saveFileDialog1.Filter = filter;
        const string header = "Animal_Name,Hair,Feathers,Eggs,Milk,Airborne,Aquatic,Predator,Toothed,Backbone,Breathes,Venomous,Fins,Legs,Tail,Domestic,Catsize,Type";
        StreamWriter writer = null;

        if (saveFileDialog1.ShowDialog() == DialogResult.OK)
        {
            filter = saveFileDialog1.FileName;
            writer = new StreamWriter(filter);

            writer.WriteLine(header);

            writer.Close();
        }

You use the SavefileDialog property "Filter" to define your list to filter by.



来源:https://stackoverflow.com/questions/5494651/saving-data-from-a-query-as-a-csv-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!