I'm working with window forms on c# I'm trying to open a file using openfile dialog when I browse to my file and open it the open file dialog keeps on showing many times .
That's my code for opening a file :
private void OpenBtn_Click(object sender, EventArgs e)
{
// Create OpenFileDialog
OpenFileDialog dlg = new OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".xml";
dlg.Filter = "XML Files (*.xml)|*.xml";
// Display OpenFileDialog by calling ShowDialog method
DialogResult result = dlg.ShowDialog();
if (result == DialogResult.OK)
{
pathtext.Text = dlg.FileName;
sourceName = dlg.FileName;
}
// destFile = resultFile.Name;
if (pathtext.Text != null)
{
createBtn.Enabled = true;
}
}
and this event handler of the method in the form load
OpenBtn.Click += new EventHandler(this.OpenBtn_Click);
I can't see where did I miss the thing.
The only way I can reproduce your bug is when I double click the button in the designer so that it creates an automatic event handler which you can see in the event properties:
If I then in addition to that add inside the code a manual registration of the event Click for example in the Load event:
private void Form1_Load(object sender, EventArgs e)
{
button2.Click += new EventHandler(this.OpenBtn_Click);
}
Then I will get the behaviour that the dialog pops up twice. If I do it one more time:
private void Form1_Load(object sender, EventArgs e)
{
button2.Click += new EventHandler(this.OpenBtn_Click);
button2.Click += new EventHandler(this.OpenBtn_Click);
}
It will pop up 3 times! It is very likely that you register this event in a loop. So when the first one is executed all others just follow up. Remove the manual registering line and put the event handler name simply into the event properties.
EDIT: The main problem is the operator += it adds the delegates to an internal list as described in this answer.
Related
Question: Is there any way to detect the occurrence of a file load in a RichTextBox (RTB) of a WPF app? I haven't find such an event in this list of events; or maybe there is some event in that list that can be used for a work around to achieve the following:
Background I'm allowing user to load a file in the RTB and close it after making changes (if needed). But before the user closes the file my app checks if the changes were made by placing bTextChanged flag in the TextChanged event. But I noticed that the TextChanged event is triggered even when a file is loaded. And even worst, the event is triggered for every character of the newly loaded file - that eventually can degrade the performance of the app if the loaded file is too long. so maybe there is a work around to make the TextChanged event triggered only when a text in the file is changed after the file was loaded.
public partial class MainWindow : Window
{
string sgFileName = "";
bool bTextChanged = false;
....
....
private void BtnOpenFile_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Rich Text Format (*.rtf)|*.rtf|All files (*.*)|*.*";
if (dlg.ShowDialog() == true)
{
sgFileName = dlg.FileName;
FileStream fileStream = new FileStream(sgFileName, FileMode.Open);
TextRange range = new TextRange(mainRTB.Document.ContentStart, mainRTB.Document.ContentEnd);
range.Load(fileStream, DataFormats.Rtf);
}
}
private void MainRTB_TextChanged(object sender, TextChangedEventArgs e)
{
bTextChanged = true;
}
private void BtnCloseDocument_Click(object sender, RoutedEventArgs e)
{
if (bTextChanged)
{
MessageBoxResult result = MessageBox.Show("Content has changed, do you want to save the changes?", "Content has Changed!", MessageBoxButton.YesNoCancel);
switch (result)
{
....
}
}
}
....
....
}
I am still only just learning C# in Visual Studio and I am trying to make a simple text encryption application. My problem at the moment is that when I use the command:
File.WriteAllText(name, inputTextBox.Text);
(Where name is the name of the file chosen in a SaveFileDialog and inputTextBox.Text is the text in a textbox on the main form)
however the file is never actually created. I even tried to build the application and run it as administrator but nothing happened.
What's even weirder is when I opened File Explorer, in the Quick Access section where it shows recent files, all the files that were supposed to be created show up there but don't exist when I click "Open File Location" and if I just try to open them, notepad just tells me the file doesn't exist.
The files are also not in my recycle bin or anything.
Here's the rest of my code in case it's something wrong with that:
public Form1()
{
InitializeComponent();
}
private void saveButton_Click(object sender, EventArgs e)
{
saveDialog.ShowDialog();
}
private void saveDialog_FileOk(object sender, CancelEventArgs e)
{
string name = saveDialog.FileName;
File.WriteAllText(name, inputTextBox.Text);
}
And in case you're wondering saveDialog is already an element in my form so there's no problem with that.
Since in your posted code the initialization of the SaveFileDialog is missing, and you say in your comment that the Debugger doesn't halt in the event body I take the long shot to assume that the event is not registered appropriately.
Try to make sure that your class (minimally) looks like the following example:
public partial class Form1 : Form
{
SaveFileDialog saveDialog;
public Form1()
{
InitializeComponent();
// create instance of SaveFileDialog
saveDialog = new SaveFileDialog();
// registration of the event
saveDialog.FileOk += SaveDialog_FileOk;
}
private void saveButton_Click(object sender, EventArgs e)
{
saveDialog.ShowDialog();
}
private void saveDialog_FileOk(object sender, CancelEventArgs e)
{
string name = saveDialog.FileName;
File.WriteAllText(name, inputTextBox.Text);
}
}
If your problem still remains, then I will remove my answer
First, I am using Visual Studio 2013 and coding in C# to develop a Windows Form Application. I have added the "System.IO" namespace.
I need to show a directory path in a textbox when selected by the user.
The code works correctly to where the user selects a folder from a popup
and presses the OK button, which then displays the number of files within
that folder -- but the folder path does NOT get displayed as I desired.
Code looks like this:
private void button1_Click(object sender, EventArgs e)
{
//
// This event handler was created by clicking the button in the application GUI.
//
DialogResult button1_Click = folderBrowserDialog1.ShowDialog();
if (button1_Click == DialogResult.OK)
{
//
// The user selected a folder and pressed the OK button.
// A message pops up and identifies the number of files found within that folder.
//
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
MessageBox.Show("Files found: " + files.Length.ToString(), "Message");
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
string path;
path = folderBrowserDialog1.SelectedPath;
// folderBrowserDialog1.ShowDialog(); // NOT SURE ABOUT USING THIS!
textBox1.Text = path;
}
You could just add this to the end of your button1_Click method (inside the if block):
textBox1.Text = folderBrowserDialog1.SelectedPath;
How can i add the mechanism in my downloader for the case although many threads on SO deals either with php etc and not upto the need.
I have a browse button at the front of a textbox where i get's the user entered Path on local drive to fix the location for downloading but i have already hardcoded one for system drive.I want textbox button to be disabled unless user clciks browse button and then new path can be entered for downloading after then.
How can i go?
A quick example:
private void browseButton_Click(object sender, EventArgs e)
{
var saveFileDialog = new System.Windows.Forms.SaveFileDialog();
var selectedPath= saveFileDialog.ShowDialog();
if (selectedPath == System.Windows.Forms.DialogResult.OK)
{
_savePath = saveFileDialog.FileName;
textBox1.Enabled = true;
textBox1.Text = _savePath;
}
}
I have the following code and am still experiencing a "Dialogs must be user-initiated" exception on the ofd.ShowDialog();
private void btnOpen_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = ALLOWED_FILE_TYPES;
ofd.FilterIndex = 1;
ofd.Multiselect = false;
bool? userClickedOK = ofd.ShowDialog();
if (userClickedOK == true)
{.....}
}
From MSDN:
In addition, there is a limit on the time allowed between when the user initiates the dialog and when the dialog is shown. If the time limit between these actions is exceeded, an exception will occur.
I can't see how the few lines after the click event is taking up this time limit.
Any suggestions on how to avoid this?
Thanks
Ok, have not tested this myself but maybe I found a hint in a quite similar SO question/answer:
private OpenFileDialog OpenFileDialog {get;set;}
public Ctor()
{
OpenFileDialog = new OpenFileDialog();
}
private void btnOpen_Click(object sender, RoutedEventArgs e)
{
...
... OpenFileDialog.ShowDialog();
...
}
Instantiate the dialog in the constructor and only call the ShowDialog method inside your button click handler without instantiating a new dialog.
[Edit]
That's the question/answer I mentioned.
I found the cause of this.
The Loaded event is being subscribed to in the constructor, and while the constructor is called just once for the control, the loaded even is being called twice and hence the btnOpen_Click event is being subscribed to twice.
I can fix it by unsubscribing from the loaded event in the control unloaded event but I'm still not sure why the Loaded is being called twice.