C# Winform Retry - c#

I have a problem with a Retry form. With this Form, I'm able to load a file from the internet. When it's done the main form pops up again. So far so good.
But when the user presses cancel, the save dialog pops up again. But what I want when the user presses the cancel button, he returns to the main form.
It Should be in this part, I think:
if (saveFileDialog1.ShowDialog() == DialogResult.Cancel)
{
return Result.Cancelled;
}
This is a part of my code:
try
{
// Create a form to select objects.
DialogResult result = System.Windows.Forms.DialogResult.None;
while (result == DialogResult.None || result == DialogResult.Retry)
{
// Picking Objects.
if (result == DialogResult.Retry)
{
System.Windows.Forms.SaveFileDialog saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
saveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.FileName = "test";
saveFileDialog1.Filter = "Family Files (*.rfa)|*.rfa|All Files (*.*)|*.*";
saveFileDialog1.FilterIndex = 1;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string address = "http://www.autodesk.com/revit-basic-sample-family-2017-enu?_ga=2.28765692.1750602280.1538397390-459409917.1521646598";
System.Net.WebClient webClient = new System.Net.WebClient();
webClient.DownloadFile(address, saveFileDialog1.FileName);
}
Autodesk.Revit.DB.Family family = null;
using (Transaction tx = new Transaction(doc))
{
tx.Start("Load Family");
if (doc.LoadFamily(saveFileDialog1.FileName, out family))
{
String name = family.Name;
TaskDialog.Show("Revit", "Family file " + name + " has been loaded " );
}
else
{
TaskDialog.Show("Revit", "Can't load the family file or already exists.");
}
tx.Commit();
}
if (saveFileDialog1.ShowDialog() == DialogResult.Cancel)
{
return Result.Cancelled;
}
}
// Show the dialog.
using (pickForm selectionForm = new pickForm(commandData))
{
result = selectionForm.ShowDialog();
}
}
return Result.Succeeded;

Everytime you call saveFileDialog1.ShowDialog() the dialog is opened. You need to store the result of the call for later checks:
if (result == DialogResult.Retry)
{
System.Windows.Forms.SaveFileDialog saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
saveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.FileName = "test";
saveFileDialog1.Filter = "Family Files (*.rfa)|*.rfa|All Files (*.*)|*.*";
saveFileDialog1.FilterIndex = 1;
// store result of the dialog
var dialogResult = saveFileDialog1.ShowDialog();
if (dialogResult == DialogResult.OK)
{
// ...
}
// ...
// compare the result without opening the dialog again.
if (dialogResult == DialogResult.Cancel)
{
return Result.Cancelled;
}

I think you can easily use if ... else statement for this like below :
System.Windows.Forms.SaveFileDialog saveFileDialog1 = new SaveFileDialog();
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
// your code
}
else // For Cancel
{
return Result.Cancelled;
}

Related

C# Button with DialogResult Retry

I'm going to use two buttons that have a DialogResult Retry. When you push the button the winform will hide, do something and it pops-up again. I use the While method for this. But if you have two buttons with a retry this won't work unless you set one button DialogResult to Yes and do a While method. But is there a better way to do this, case switch or something?
Note this is within a Class
try
{
// Create a form to select objects.
DialogResult result = System.Windows.Forms.DialogResult.None;
while (result == DialogResult.None || result == DialogResult.Retry)
{
// Picking Objects.
if (result == DialogResult.Retry)
{
System.Windows.Forms.SaveFileDialog saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
saveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.FileName = "test";
saveFileDialog1.Filter = "Family Files (*.rfa)|*.rfa|All Files (*.*)|*.*";
saveFileDialog1.FilterIndex = 1;
var dialogResult = saveFileDialog1.ShowDialog();
if (dialogResult == DialogResult.OK)
{
string address = "http://www.autodesk.com/revit-basic-sample-family-2017-enu?_ga=2.28765692.1750602280.1538397390-459409917.1521646598";
System.Net.WebClient webClient = new System.Net.WebClient();
webClient.DownloadFile(address, saveFileDialog1.FileName);
Autodesk.Revit.DB.Family family = null;
using (Transaction tx = new Transaction(doc))
{
tx.Start("Load Family");
if (doc.LoadFamily(saveFileDialog1.FileName, out family))
{
String name = family.Name;
TaskDialog.Show("Revit", "Family file " + name + " has been loaded ");
}
else
{
TaskDialog.Show("Revit", "Can't load the family file or already exists.");
}
tx.Commit();
}
}
if (dialogResult == DialogResult.Cancel)
{
}
}
// Show the dialog.
using (testForm selectionForm = new vuurenForm(commandData))
{
result = selectionForm.ShowDialog();
}
}
return Result.Succeeded;
You may set the DialogResult in the code, not in the form designer. Just double click the buttons and add something like:
private void button1_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Retry;
}
That way both buttons will have the same DialogResult.
Than the loop is OK with only checking for the DialogResult.Retry.
Exactly you can try this code to manage your DialogResult like:
switch(MessageBox.Show("Text", "Title", MessageBoxButtons.YesNo))
{
case DailogResult == DialogResult.Yes:
//Do something
case DailogResult == DialogResult.Retry:
//Do something
}
Actually for two Button objects you have to have two event-handler objects and you can set:
DialogResult = DialogResult.Retry;
In the event that you want to Retry.
You can try this:
var dialogResult = DialogResult.Retry;
while (dialogResult == DialogResult.Retry) {
try {
CheckSomething();
break;
}
catch {
if (dialogResult == DialogResult.Abort) {secondDialog.DialogResult = Retry;}
throw;
}
}
You can also use enums like below:
enum Result {Ignore, Abort,Retry};

Custom checking file name on SaveFileDialog

I have a SaveFileDialog.
When the user clicks on OK I have to check if there is a similar file name.
The system has been doing such a test, but I need to add a test Is there a file with a similar name and numbering.
For example, if the user selected a file name "a" and there is a file "a1" or "a2", warning message should appear. (as it appears when there is a file named "a").
Is there a way to do this?
SaveFileDialog inherits FileDialog class which has FileOk event. You can put logic to check if similar files already exist in the handler method for this event. If the result is true, display warning message. Then if user choose No from the warning dialog, set Cancel property of CancelEventArgs parameter to True, this will prevent save file dialog window from closing :
var dlg = new SaveFileDialog();
dlg.FileOk += (o, args) =>
{
var file = dlg.FileName;
if (isSimilarFileExist(file))
{
var result = MessageBox.Show("Similar file names exist in the same folder. Do you want to continue?",
"Some dialog title",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning
);
if(result == DialogResult.No)
args.Cancel = true;
}
};
dlg.ShowDialog();
......
private bool isSimilarFileExist(string file)
{
//put your logic here
}
this is the answer you want
SaveFileDialog S = new SaveFileDialog();
if(S.ShowDialog() == DialogResult.OK)
{
bool ShowWarning = false;
string DirPath = System.IO.Path.GetDirectoryName(S.FileName);
string[] Files = System.IO.Directory.GetFiles(DirPath);
string NOFWE = DirPath+"\\"+System.IO.Path.GetFileNameWithoutExtension(S.FileName);
foreach (var item in Files)
{
if (item.Length > NOFWE.Length && item.Substring(0, NOFWE.Length) == NOFWE)
{
int n;
string Extension = System.IO.Path.GetExtension(item);
string RemainString = item.Substring(NOFWE.Length, item.Length - Extension.Length - NOFWE.Length);
bool isNumeric = int.TryParse(RemainString, out n);
if(isNumeric)
{
ShowWarning = true;
break;
}
}
}
if(ShowWarning)
{
if (MessageBox.Show("Warning alert!", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
Save();//Saving instance
}
else
{
Save();//Saving instance
}
}
ans Save() method is the saving instructions...

Doing a file I/O project and cannot seem to get my file to save

When I click on the file drop down where I have new, for new file, I prompt the user. If they have data in the textbox, if they would like to save what they have done before starting a new file. I get the save prompt dialog box to pop up and all that but I wont save the file.
private void mnuFileNew_Click(object sender, EventArgs e)
{
if (txtText.Text.Trim().Length <= 0)
{
lblStatus.ForeColor = Color.BlueViolet;
lblStatus.Text = "New file!";
}
else
{
if (MessageBox.Show("Start new file without saving?", "Exit",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No)
{
try
{
SaveFileDialog sfd = new SaveFileDialog();
// set properties
sfd.Title = "Where would you like to save this?";
sfd.InitialDirectory = #"c:\Users\public";
sfd.Filter = "Text File (*.txt)|*.txt|All files (*.*)|*.*";
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
lblStatus.Text = sfd.FileName;
lblStatus.ForeColor = Color.Navy;
}
// show a message
lblStatus.ForeColor = Color.BlueViolet;
lblStatus.Text = "The Text has been uploaded!";
}
catch (Exception ex)
{
lblStatus.ForeColor = Color.Red;
lblStatus.Text = ex.Message;
}
}
else
{
txtText.Text = "";
}
you need to create the file
if(sfd.ShowDialog() == DialogResult.OK)
{
using(StreamWriter sw = new StreamWriter(sfd.FileName))
{
sw.WriteLine(YourTextBox.Text);
}
}

How to save a chart as Image with Save File Dialog in C# Windows Forms Application

I want to save a chart as Image with Save File Dialog when a button is clicked. My Application type is c# Windows Forms Application. So that user can save the image file in any directory where he/she wishes.
I have made a work around:
private void exportAsImagebtn_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "PNG Image|*.png|JPeg Image|*.jpg";
saveFileDialog.Title = "Save Chart As Image File";
saveFileDialog.FileName = "Sample.png";
DialogResult result = saveFileDialog.ShowDialog();
saveFileDialog.RestoreDirectory = true;
if (result == DialogResult.OK && saveFileDialog.FileName != "")
{
try
{
if (saveFileDialog.CheckPathExists)
{
if (saveFileDialog.FilterIndex == 2)
{
chart.SaveImage(saveFileDialog.FileName, ChartImageFormat.Jpeg);
}
else if (saveFileDialog.FilterIndex == 1)
{
chart.SaveImage(saveFileDialog.FileName, ChartImageFormat.Png);
}
}
else
{
MessageBox.Show("Given Path does not exist");
}
}
catch(Exception ex){
MessageBox.Show(ex.Message);
}
}
}
Or like this using a dictionary for file extensions:
try
{
//Check if chart has at least one enabled series with points
if (chart1.Series.Any(s => s.Enabled && s.Points.Count>0))
{
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Image Files|*.png;";
save.Filter = "Bitmap Image (.bmp)|*.bmp|Gif Image (.gif)|*.gif|JPEG Image (.jpeg)|*.jpeg|Png Image (.png)|*.png|Tiff Image (.tiff)|*.tiff";
save.Title = "Save Chart Image As file";
save.DefaultExt = ".png";
if (save.ShowDialog() == DialogResult.OK)
{
var imgFormats = new Dictionary<string, ChartImageFormat>()
{
{".bmp", ChartImageFormat.Bmp},
{".gif", ChartImageFormat.Gif},
{".jpg", ChartImageFormat.Jpeg},
{".jpeg", ChartImageFormat.Jpeg},
{".png", ChartImageFormat.Png},
{".tiff", ChartImageFormat.Tiff},
};
var fileExt = System.IO.Path.GetExtension(save.FileName).ToString().ToLower();
if (imgFormats.ContainsKey(fileExt))
{
chart1.SaveImage(save.FileName, imgFormats[fileExt]);
}
else
{
throw new Exception(String.Format("Only image formats '{0}' supported", string.Join(", ", imgFormats.Keys)));
}
}
}
else
{
throw new Exception("Nothing to export");
}
}
catch (Exception ex)
{
MessageBox.Show("SaveChartAsImage()", ex.Message);
}

C#: Am i validating filetype and using goto in a right manner?

i have code to save a file like
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "Text files|*.txt";
SaveDialog:
if ((bool)dialog.ShowDialog()) {
if (System.IO.Path.GetExtension(dialog.FileName) != ".txt") {
MessageBox.Show("You must select a .txt file");
dialog.FileName = "";
goto SaveDialog;
}
File.WriteAllText(dialog.FileName, txtEditor.Text);
}
i read that i should not use goto. i could use do/while and check that a valid extension was selected but that will add alot of unnecessary code. i find this neater. or is there a better/more correct way?
using (SaveFileDialog dialog = new SaveFileDialog())
{
dialog.Filter = "Text files|*.txt";
while(dialog.ShowDialog() == DialogResult.OK)
if (System.IO.Path.GetExtension(dialog.FileName).ToLowerInvariant() != ".txt")
MessageBox.Show("You must select a.txt file");
else // file is ok
{
File.WriteAllText(dialog.FileName, txtEditor.Text);
break;
}
}
I would suggest the following:
using (SaveFileDialog dialog = new SaveFileDialog()) {
dialog.Filter = "Text files|*.txt";
while (true) {
if (dialog.ShowDialog() == DialogResult.OK) {
if (!System.IO.Path.GetExtension(dialog.FileName).Equals(".txt", StringComparison.InvariantCultureIgnoreCase)) {
MessageBox.Show("You must select a .txt file");
}
else {
File.WriteAllText(dialog.FileName, txtEditor.Text);
break;
}
}
else break;
}
}
While there are legitimate reasons for using the goto statement, in this case it can be avoided and replaced with a more readable solution.
Note also that you should not cast DialogResult (the return value of ShowDialog()) to bool.

Categories