Search code examples
c#excelopenfiledialog

openFileDialog Filter not showing any option and showing all the files in the folder (i.e. *.jpeg and *.xlsx)


string file = "";
int size = -1;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
openFileDialog1.Filter = "Excel |*.xlsx"; //"Excel Files|(*.xlsx, *.xls)|*.xlsx;*.xls";
openFileDialog1.FilterIndex = 1;

if(result == DialogResult.OK) // Test result.
{
    file = openFileDialog1.FileName;
    try
    {
        string text = File.ReadAllText(file);
        size = text.Length;
    }
    catch(System.IO.IOException)
    {
    }
}

tempLBL.Text = file;

I also tested the Filter which is commented above. It is not showing any filter when I browse... and Showing all the files. What I need is that when Browse button clicked then only XLSX or XLS files shown to the user.

Thanks in Advance


Solution

  • That's because you Show Dialog before setting your filters and FilterIndex.

    Your code should be like

    openFileDialog1.Filter = "Excel |*.xlsx"; //"Excel Files|(*.xlsx, *.xls)|*.xlsx;*.xls";
    openFileDialog1.FilterIndex = 1;
    DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.