When I click the button to open a file the OpenFileDialog box opens twice. The first box only opens the image files and the second box text files. If the user decides to close out the first box without choosing a file the second box pops up as well. I'm not sure what I am over looking on this issue. Any help would be appreciated. Thanks!
OpenFileDialog of = new OpenFileDialog();
of.Filter = "All Image Formats|*.jpg;*.png;*.bmp;*.gif;*.ico;*.txt|JPG Image|*.jpg|BMP image|*.bmp|PNG image|*.png|GIF Image|*.gif|Icon|*.ico|Text File|*.txt";
if (of.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
try
{
image1.Source = new BitmapImage(new Uri(of.FileName));
// enable the buttons to function (previous page, next page, rotate left/right, zoom in/out)
button1.IsEnabled = false;
button2.IsEnabled = false;
button3.IsEnabled = false;
button4.IsEnabled = false;
button5.IsEnabled = true;
button6.IsEnabled = true;
button7.IsEnabled = true;
button8.IsEnabled = true;
}
catch (ArgumentException)
{
// Show messagebox when argument exception arises, when user tries to open corrupted file
System.Windows.Forms.MessageBox.Show("Invalid File");
}
}
else if(of.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
try
{
using (StreamReader sr = new StreamReader(of.FileName))
{
textBox2.Text = sr.ReadToEnd();
button1.IsEnabled = true;
button2.IsEnabled = true;
button3.IsEnabled = true;
button4.IsEnabled = true;
button5.IsEnabled = true;
button6.IsEnabled = true;
button7.IsEnabled = true;
button8.IsEnabled = true;
}
}
catch (ArgumentException)
{
System.Windows.Forms.MessageBox.Show("Invalid File");
}
}
You're calling ShowDialog() twice:
if (of.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//...
}
else if(of.ShowDialog() == System.Windows.Forms.DialogResult.OK)
Just call it once, and save the results:
var dialogResult = of.ShowDialog();
if (dialogResult == System.Windows.Forms.DialogResult.OK)
{
//...
}
// Note that the condition was the same!
else if(dialogResult != System.Windows.Forms.DialogResult.OK)
Edit:
If you want the second dialog to only show when the first is handled, you can do:
var dialogResult = of.ShowDialog();
if (dialogResult == System.Windows.Forms.DialogResult.OK)
{
//...
// Do second case here - Setup new options
dialogResult = of.ShowDialog(); //Handle text file here
}
You are calling ShowDialog both in the if and else if condition. That method is responsible for showing the dialog and only has the nice side effect of also telling you what the user clicked.
Store the method's result in a variable and check that in your if..elseif conditions instead.
Related
Hello im having trouble with file dialog
Standard code, but it's freezing while selecting large files (600MB+ xls file that i need to first reformat to xlsb, then stream data from, but that is not important here).
What i wanted to achieve is to hide dialog when Open button is clicked, so that i could display Loading Message.
Yet im not sure how can i achieve that. Can i somehow subscribe to Open button?
OpenFileDialog openFile = new OpenFileDialog() { DereferenceLinks = false };
openFile.Title = "Select Supplier List";
openFile.Filter = "Excel files (*.*xls*)|*.*xls*";
try
{
if (openFile.ShowDialog() == true)
{
/* Takes long time to go after selection */
ViewModel.ReportPath = openFile.FileName;
ViewModel.FileTrueName = Path.GetFileName(ViewModel.ReportPath);
}
}
catch
{
ViewModel.ReportPath = null;
ViewModel.FileTrueName = null;
}
Wrapping code with task, helped :)
Some changes happened during searching for answer, based on comments.
Task.Run(() =>
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.Title = "Select Supplier List";
openFile.Filter = "Excel Files(*.xls; *.xlsx; *.xlsb; *.xlsm)| *.xls; *.xlsx; *.xlsb; *.xlsm";
try
{
if (openFile.ShowDialog() == true)
{
ViewModel.ReportPath = openFile.FileName;
ViewModel.FileTrueName = Path.GetFileName(ViewModel.ReportPath);
}
}
catch
{
ViewModel.ReportPath = null;
ViewModel.FileTrueName = null;
}
});
I am trying to make a winforms application so when something is clicked it checks a webpage for it's response.
I have tested the web page to see if it is a PHP error but it works fine from that side.
It is completely ignoring the else if statement and skips to the else statement below it even though the response is "Unassigned".
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://fms.psrpc.co.uk/apiconfirmD.php?" + ApiKey);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (response)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
if (reader.ReadToEnd() == "Changed")
{
label2.Visible = false;
button1.Enabled = false;
button2.Enabled = true;
button3.Enabled = true;
button4.Enabled = true;
button5.Enabled = true;
button6.Enabled = true;
button7.Enabled = true;
button8.Enabled = true;
timer1.Enabled = true;
}
else if (reader.ReadToEnd() == "Unassigned")
{
string message = "Error Code: B66794O37945O46791K##Error booking on.#Please make sure you have been assigned to a vehicle.##If this error persists please contact K.McCrudden.";
message = message.Replace("#", "" + System.Environment.NewLine);
string title = "Error!";
MessageBoxButtons buttons = MessageBoxButtons.OK;
DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
}
else
{
string message = "Error Code: B002875O46883O84655K##Error booking on.#Please make sure you have booked a shift and have been assigned.##If this error persists please contact K.McCrudden.";
message = message.Replace("#", "" + System.Environment.NewLine);
string title = "Error!";
MessageBoxButtons buttons = MessageBoxButtons.OK;
DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
}
}
}
No, it is not being ignored. You are reading all the data in your first if block by calling reader.ReadToEnd(). This way, there is no further data available to read in your else if statement; it returns empty string. Thus condition does not match and final else block gets executed.
Modify the code something like below. Notice the temporary data variable in below code.
StreamReader reader = new StreamReader(response.GetResponseStream());
string data = reader.ReadToEnd();//Read the data in temp variable.
//Use this variable to check the conditions further.
if (data == "Changed")
{
//Your code here
}
else if (data == "Unassigned")
{
//Your code here
}
else
{
//Your code here
}
You have an error in your general logic. When you enter the first if statement, you're reading to the end of the stream with the code reader.ReadToEnd(). In the next statement (the else), you're reading the stream again, but it has already been read, so it will return an empty string, thus the last else statement will effectively be hit.
You can also read about this on MSDN: StreamReader.ReadToEnd() Method.
Definition of the return value:
The rest of the stream as a string, from the current position to the end. If the current position is at the end of the stream, returns an empty string ("").
Your code should look like this:
StreamReader reader = new StreamReader(response.GetResponseStream());
var result = reader.ReadToEnd();
if(result == "Changed")
{
label2.Visible = false;
button1.Enabled = false;
button2.Enabled = true;
button3.Enabled = true;
button4.Enabled = true;
button5.Enabled = true;
button6.Enabled = true;
button7.Enabled = true;
button8.Enabled = true;
timer1.Enabled = true;
}
else if(result == "Unassigned")
{
string message = "Error Code: B66794O37945O46791K##Error booking on.#Please make sure you have been assigned to a vehicle.##If this error persists please contact K.McCrudden.";
message = message.Replace("#", "" + System.Environment.NewLine);
string title = "Error!";
MessageBoxButtons buttons = MessageBoxButtons.OK;
DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
}
else
{
string message = "Error Code: B002875O46883O84655K##Error booking on.#Please make sure you have booked a shift and have been assigned.##If this error persists please contact K.McCrudden.";
message = message.Replace("#", "" + System.Environment.NewLine);
string title = "Error!";
MessageBoxButtons buttons = MessageBoxButtons.OK;
DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
}
Im trying to use the openFileDialog to load in 2 different files that goes to 2 different area. I trying doing 2 ways, first i try adding an if statement to see which file they select and use that expression, but it gives me an error.
OpenFileDialog opendi = new OpenFileDialog();
opendi.Filter = "xml|*.xml";
if (opendi.ShowDialog() == DialogResult.OK)
{
if (opendi.FileName == Hotel_Filename)
{
hotelListData = HotelList.HotelLoadFile(opendi.FileName);
lblStatus.Text = "Success";
}
}
else
{
rmtp = roomtypedata.LoadFile(opendi.FileName);
lblStatus.Text = "Success";
}
and if i do this way , it works, but i have to load the files in the right order, or else if i load the 2nd one first , i get an error. so is there a better method to this?
OpenFileDialog opendi = new OpenFileDialog();
opendi.Filter = "xml|*.xml";
if (opendi.ShowDialog() == DialogResult.OK)
{
hotelListData = HotelList.HotelLoadFile(opendi.FileName);
lblStatus.Text = "Success";
}
if (opendi.ShowDialog() == DialogResult.OK)
{
rmtp = roomtypedata.LoadFile(opendi.FileName);
lblStatus.Text = "Success";
}
Ok, the problem seems to be with checking the file name. You want to compare only the file name,not all the path. Try this:
Hotel_Filename = "hotels.xml"
....
for (int=0;i<2;i++)
{
OpenFileDialog opendi = new OpenFileDialog();
opendi.Filter = "xml|*.xml";
if (opendi.ShowDialog() == DialogResult.OK)
{
if (Path.GetFileName(opendi.FileName) == Hotel_Filename)
{
hotelListData = HotelList.HotelLoadFile(opendi.FileName);
lblStatus.Text = "Success";
}
else
{
rmtp = roomtypedata.LoadFile(opendi.FileName);
lblStatus.Text = "Success";
}
}
}
In top of form1 i did
OpenFiledialog openFileDialog1 = new OpenFiledialog();
Then:
private void changeWorkingDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
openFileDialog1.Filter =
"BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff|"
+ "All Graphics Types|*.bmp;*.jpg;*.jpeg;*.png;*.tif;*.tiff";
openFileDialog1.InitialDirectory = #"c:\";
openFileDialog1.Multiselect = true;
if (result == DialogResult.OK)
{
string[] files = openFileDialog1.FileNames;
try
{
if (files.Length > 0)
{
label6.Text = files.Length.ToString();
label6.Visible = true;
string directoryPath = Path.GetDirectoryName(files[0]);
label12.Text = directoryPath;
label12.Visible = true;
}
}
catch (IOException)
{
}
}
}
But when i click the button the init directory is documents and not c: and i don't see the filter/s at all but i see all the files. It's like the settings i did didn't effect.
ShowDialog is modal, so it waits until the user clicks OK/Cancel.
Only then does the rest of your code run.
You should only call ShowDialog after you have finished setting the properties:
openFileDialog1.Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg...";
openFileDialog1.InitialDirectory = #"c:\";
openFileDialog1.Multiselect = true;
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
Your logic is incorrect. You're displaying the dialog before you configure the settings.
// Configure it first
openFileDialog1.Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff|"
+ "All Graphics Types|*.bmp;*.jpg;*.jpeg;*.png;*.tif;*.tiff";
openFileDialog1.InitialDirectory = #"c:\";
openFileDialog1.Multiselect = true;
// Then show it and wait for the user to make a selection or cancel
DialogResult result = openFileDialog1.ShowDialog();
// Take some action if the user made a selection
if (result == DialogResult.OK)
{
...
As a side note, be careful about eating exceptions. At the least, log the error and inform the user.
catch (IOException ex)
{
// log ex.ToString() somewhere
MessageBox.Show("An error has occurred!\r\n\r\n" + ex.Message);
}
The problem is you are calling ShowDialog() before settings the properties, this should work for you:
openFileDialog1.Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff|"
+ "All Graphics Types|*.bmp;*.jpg;*.jpeg;*.png;*.tif;*.tiff";
openFileDialog1.InitialDirectory = #"c:\";
openFileDialog1.Multiselect = true;
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string[] files = openFileDialog1.FileNames;
try
{
if (files.Length > 0)
{
label6.Text = files.Length.ToString();
label6.Visible = true;
string directoryPath = Path.GetDirectoryName(files[0]);
label12.Text = directoryPath;
label12.Visible = true;
}
}
catch (IOException)
{
}
}
I am trying to write notepad, how do I know if user clicked 'Cancel'? My code doesn't work:
private void SaveAsItem_Click(object sender, EventArgs e)
{
saveFileDialog1.FileName = "untitled";
saveFileDialog1.Filter = "Text (*.txt)|*.txt";
saveFileDialog1.ShowDialog();
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(saveFileDialog1.FileName);
SaveFile.WriteLine(richTextBox1.Text);
SaveFile.Close();
if (DialogResult == DialogResult.Cancel)
{
richTextBox1.Text = "CANCEL";
issaved = false;
}
else
{
issaved = true;
}
}
You're checking the DialogResult property for your main form, but it's the child form that you want to check. So...
var dr = saveFileDialog1.ShowDialog();
if( dr == DialogResult.OK )
{
using(var SaveFile = new StreamWriter(saveFileDialog1.FileName))
{
SaveFile.WriteLine(richTextBox1.Text);
issaved = true;
}
}
else // cancel (or something else)
{
richTextBox1.Text = "CANCEL";
issaved = false;
}
Also, you should wrap your StreamWriter in a using block as I have done above. Your code will fail to close the file if an exception occurs. A using block is syntactic sugar for a try/finally block which calls Dispose() (which in turn calls Close()) in the finally portion.
DialogResult res = saveFileDialog1.ShowDialog();
if (res == DialogResult.Cancel) {
// user cancelled
}
else {
// Write file to disk using the filename chosen by user
}
You are creating the file before checking the result of the dialog. Move the SaveFile variable bit into the "issaved = true" block.
[edit] And as the others said, check the Dialog result properly