Al2110
Al2110

Reputation: 576

Getting chosen file type from SaveFileDialog

In the SaveFileDialog with WinForms, I provide the option to save an Excel file or csv file. How can I get the option selected?

SaveFileDialog exportDialog = new SaveFileDialog();
exportDialog.Filter = "Excel spreadsheet (*.xlsx)|*.xlsx|Comma-separated values file (*.csv)|*.csv";

if (exportDialog.Filter.ShowDialog() == DialogResult.OK)
{
    // do something based on chosen file type
}

Upvotes: 1

Views: 1198

Answers (1)

Akhilesh Mishra
Akhilesh Mishra

Reputation: 6140

You can achieve it by using FilterIndex of SaveFileDialog like this:

SaveFileDialog exportDialog = new SaveFileDialog();
exportDialog.Filter = "Excel spreadsheet (*.xlsx)|*.xlsx|Comma-separated values file (*.csv)|*.csv";

 
            if (exportDialog.ShowDialog() == DialogResult.OK)
            {
                if (exportDialog.FilterIndex == 1)
                {
                    MessageBox.Show("Excel");
                }

                if (exportDialog.FilterIndex == 2)
                {
                    MessageBox.Show("CSV");
                }
            }

Note: Index of items will start from 1.

Upvotes: 3

Related Questions