openFileDialog_FileOK is never called in C#

I want to print the name of the selected file on label1 when the FileDialog closes successfully using the openFileDialog_FileOk in C#, but the openFileDialog_FileOK is never called.
Sorry for bad English.

namespace Graph_Win_Forms
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.ShowDialog();
        }

        private void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
        {
            label1.Text = "Dosya: " + openFileDialog1.FileName;
        }
    }
}

I tried delete code and WinForms Element but it didn’t work

>Solution :

I suspect that you have copied that code from an online sample somewhere and you have ignored the fact that, if you expect that method to be invoked when an event is raised, you need to register it as an event handler. The most immediate option would be this:

OpenFileDialog openFileDialog1 = new OpenFileDialog();

openFileDialog1.FileOk += openFileDialog1_FileOk;
openFileDialog1.ShowDialog();

More to follow…

Leave a Reply