
C# openfiledialog filter application example
Click Browse to open a file selection dialog box in the software, which is realized by the OpenFileDialog control. Of course, OpenFileDialog itself does not have a browser, and a button must be added as the button to open the file selection dialog box.
There are not many properties of the OpenFileDialog control in C#. Usually there are only a few properties that need to be set, such as InitialDirectory, RestoreDirectory, Filter, FilterIndex, Multiselect, etc. Let's look at a specific application example.
C# openfiledialog filter application example:
1. Drag an OpenFileDialog control to the Form and keep the default name openFileDialog1(or change it to another name).
2. Drag another TextBox control to the Form, keep the default name textBox1, and drag it longer to show the long path.
3. Finally drag a Button control to the Form, keep the default name button1, change its Text property to "Browse", double-click button1 to open the code-behind file.
4. Add code(complete code) in the private void button1_Click(object sender, EventArgs e) method:
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.InitialDirectory = @"C:\";//Initial display directory
//Whether to locate the last opened directory for the next open dialog
openFileDialog1.RestoreDirectory = true;
//Filter file types
openFileDialog1.Filter = "Text file (*.txt)|*.txt|All files (*.*)|*.*";
//FilterIndex is associated with Filter and is used to set the file type displayed by default
openFileDialog1.FilterIndex = 1;//The default is 1, the file type displayed by default is *.txt; if it is set to 2, the file type displayed by default is *.*
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//Assign the selected file to the textbox
textBox1.Text = openFileDialog1.FileName;
}
}
The above code passed the test in Visual Studio 2019, and the running effect is as follows:
-
Related Reading
- Winforms dynamically add controls with code
- C# label control, with winforms label transparent ba
- C# Winforms textbox focus(2 methods)
- C# Winforms Resources add, modify and delete
- C# Winforms panel border, with color, style, thickne
- C# Winforms custom TextBox control, limit the length
- C# Winforms listview show table(adaptive column widt
- C# Winforms open folder and select the specified fil
- C# open url in default browser in c# windows applica