问题
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