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
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:
What was likely done in the first place was that an
OpenFileDialogwas added to the form in the designer and then the event handler generated in the designer. You could do that too, instead of creating theOpenFileDialogin code. If you do that, you can select an existing method in the designer rather than creating a new one.Having said that, I would normally not handle that event anyway. If you're displaying one or more dialogues in different places and you want to write the code to execute on OK in one place then it makes sense to handle that event. It would also make sense if the event handler was in a different code file to the code that shows the dialogue. If you are only display the dialogue in one place though, I'd probably just check the result of
ShowDialogand act onOK.