Right now I have a main form that copies a file to another directory.
I want to handle the case 'a file of the same name already exists' in a catch statement.
I want this to be done by it popping up another window asking whether to replace or keep via buttons. Then using an if statement to check which button was clicked
Current code:
catch (IOException x)
{
Copy copy = new Copy();
copy.ShowDialog();
}
Goal:
catch (IOException x)
{
Copy copy = new Copy();
copy.ShowDialog();
if (//Replace button was clicked)
do this
else if (//Keep button was clicked)
do this
}
I can't seem to find the methods that serve this purpose.
You could make your Copy dialog return the DialogResult when the button is clicked. For instance you could use DialogRsult.OK for the Replace button and the DialogResult.Cancel for the Keep button. Something like this:
When clicked Replace button within the Copy dialog you can set this within the Replace_Click event handler
this.DialogResult = DialogResult.OK;
this.Close();
set in the similar way the DialogResult.Cancel in the Keep_Click event handler
and you could call your dialog like this:
Copy copy = new Copy();
DialogResult dr = copy.ShowDialog();
if(dr == DialogResult.OK)
//Replace clicked
else if(dr == DialogResult.Cancel)
//Keep clicked
You should consider using the DialogResult class instead.
You want something like this:
catch (IOException x)
{
DialogResult dr = new DialogResult ();
dr.ShowDialog();
if (dr == DialogResult.OK)
MessageBox.Show ("File replaced.");
else if (dr == DialogResult.Cancel)
MessageBox.Show ("File kept.");
}
Do not use exceptions to handle this kind of situations.
Just test if file exists and use a simple MessageBox with YesNo buttons
sourceFile = "Your_Source_File_To_Copy";
string destFile = Path.Combine(destFolder, Path.GetFileName(sourceFile));
if(File.Exists(destFile))
{
DialogResult dr = MessageBox.Show("File already exist! Do you wish to overwrite?",
"Warning!",
MessageBoxButtons.YesNo);
if(dr == DialogResult.Yes)
// Overwrite
else
// Do something else
}
As Mr Lippert says in this answer,
Exceptions are there to
help you debug your program, not to control its flow.
Have you looked into the Form.ShowDialog method?
http://msdn.microsoft.com/en-us/library/c7ykbedk.aspx
Code Excerpt from MSDN:
public void ShowMyDialogBox()
{
Form2 testDialog = new Form2();
// Show testDialog as a modal dialog and determine if DialogResult = OK.
if (testDialog.ShowDialog(this) == DialogResult.OK)
{
// Read the contents of testDialog's TextBox.
this.txtResult.Text = testDialog.TextBox1.Text;
}
else
{
this.txtResult.Text = "Cancelled";
}
testDialog.Dispose();
}
Check for the file existence before copying:
if (File.Exists(destFileName))
{
Copy copy = new Copy();
System.Windows.Forms.DialogResult res = copy.ShowDialog();
if (res == System.Windows.Forms.DialogResult.Yes)
File.Copy(sourceFileName, destFileName, true);
}
else
{
File.Copy(sourceFileName, destFileName);
}
Also set the DialogResult property in the Copy form appropriately.
Perhaps implementing your own result is what you are looking for.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var result = new Form2().ShowDialog();
MessageBox.Show(result.ToString());
}
}
public partial class Form2 : Form
{
ButtonResult buttonResult;
public Form2()
{
InitializeComponent();
}
public new ButtonResult ShowDialog()
{
base.ShowDialog();
return buttonResult;
}
private void KeepButton_Click(object sender, EventArgs e)
{
buttonResult = ButtonResult.Keep;
this.Close();
}
private void ReplaceButton_Click(object sender, EventArgs e)
{
buttonResult = ButtonResult.Replace;
this.Close();
}
}
public enum ButtonResult
{
None = 0,
Keep = 1,
Replace = 2,
}
Related
It (MessageBox) checks if a file is saved or not
I want to close the Form when clicking Yes
and to return to the app when clicking No
I searched a lot in the documents and questions but didn't find an answer
I mean, there is "MessageBox.Show()",
Isn't there "MessageBox.Close()" ??
That's what I have:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
var message = "The File Is Not Saved\nDo You Want To Close?";
var title = "File Not Saved";
var buttons = MessageBoxButtons.YesNo;
if (FSaved == false)
{
var res = MessageBox.Show(message, title, buttons);
if (res == DialogResult.Yes)
{
this.Close();
}
else if (res == DialogResult.No)
{
return;
}
}
}
You have you cancel the close with the event args - e.
e.Cancel = true;
You also shouldn't call Close() from FormClosing as it is already on the way out.
I want to show a message before selecting another tab if Message result is 'NO' then it should remain in the current tab if message result is YES then selected tab should open.
I have tried following code.
''
'private void tbRWINV_Selected(object sender, TabControlEventArgs e){
if (dgvSaleReturnWintoutInvoice.Rows.Count > 0)
{
DialogResult msg = new DialogResult();
msg = MessageBox.Show("The data entered for return will be lost if you move to other Tab", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (msg == DialogResult.No)
{
tbRWINV.TabIndex = 1;
}
}
}
'''
The TabControlCancelEventArgs event object has a bool Cancel property that will cancel the tab change. E.g:
public class MyForm : Form {
TabControl tc = new TabControl();
public MyForm() {
//...
tc.Selecting += tc_Selecting;
}
void tc_Selecting(object sender, TabControlCancelEventArgs e) {
DialogResult r = MessageBox.Show(this, "Are you sure you want to change tabs?", "Confirm", MessageBoxButtons.YesNo);
e.Cancel = (r == DialogResult.No);
}
}
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};
i have an update form which opens as showDialog. i notice when i click on save my update process goes through, closes form and refresh datagrid on parent form and when cancel button is click it closes form and also refreshes datagrid. how do i prevent datagrid from refresh when cancel button is clicked, am thinking of doing a public int declaration to return 1 when save is clicked and 0 when cancel is clicked but can't figure out how to do so. below is code for calling update form from parent form
private void kryptonDataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
try
{
frmUpdate f2 = new frmUpdate();
f2.lblClientID.Text = kryptonDataGridView1.SelectedRows[0].Cells["ClientID"].Value.ToString();
f2.lblClearinAgentID.Text = kryptonDataGridView1.SelectedRows[0].Cells["Clearing_Agent_ID"].Value.ToString();
f2.textboxClientCode.Text = kryptonDataGridView1.SelectedRows[0].Cells["Client Code"].Value.ToString();
f2.txtboxClientName.Text = kryptonDataGridView1.SelectedRows[0].Cells["Client Name"].Value.ToString();
f2.txtboxPostalAddress.Text = kryptonDataGridView1.SelectedRows[0].Cells["Postal Address"].Value.ToString();
f2.txtboxTelephone.Text = kryptonDataGridView1.SelectedRows[0].Cells["Telephone"].Value.ToString();
f2.txtboxFax.Text = kryptonDataGridView1.SelectedRows[0].Cells["Fax"].Value.ToString();
f2.txtboxEmailAddress1.Text = kryptonDataGridView1.SelectedRows[0].Cells["E-mail Address 1"].Value.ToString();
f2.txtboxEmailAddress2.Text = kryptonDataGridView1.SelectedRows[0].Cells["E-mail Address 2"].Value.ToString();
f2.txtboxEmailAddress3.Text = kryptonDataGridView1.SelectedRows[0].Cells["E-mail Address 3"].Value.ToString();
f2.txtboxWebsite.Text = kryptonDataGridView1.SelectedRows[0].Cells["Website"].Value.ToString();
f2.txtboxChargeRate.Text = kryptonDataGridView1.SelectedRows[0].Cells["Charge Rate"].Value.ToString();
//f2.lblTotalDeposit.Text = kryptonDataGridView1.SelectedRows[0].Cells["Total Deposit"].Value.ToString();
//f2.lblAccountBal.Text = kryptonDataGridView1.SelectedRows[0].Cells["Account Balance"].Value.ToString();
f2.ShowDialog();
kryptonbtnDelete.Enabled = false;
private void kryptonbtnEdit_Click(object sender, EventArgs e)
{
kryptonDataGridView1_CellDoubleClick(null, null);
}
and inside update form which displays as dialog to parent form i tried something like that
private void kryptonCancel_Click(object sender, EventArgs e)
{
frmUpdate_FormClosing(null,null);
}
private void frmUpdate_FormClosing(object sender, FormClosingEventArgs e)
{
if (DialogResult != DialogResult.OK)
{
return;
}
else
{
e.Cancel = true;
}
}
dialog result from save click method
DialogResult result = MessageBox.Show("Do you want to Update this Client?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
MessageBox.Show("Client information successfully Updated", "Updating Client(s) Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
int rowsUpdated = cmd.ExecuteNonQuery();
if (rowsUpdated > 0)
{
}
}
else if (result == DialogResult.No)
{
return;
}
The return value of a call to Form.ShowDialog is a DialogResult value. This value is taken by the Form engine directly from the DialogResult property of the Button clicked. If the button has any value for this property different from DialogResult.None then this button will close the form and its DialogResult property is returned by the call to ShowDialog()
So if you have a button on your frmUpdate with its DialogResult set to OK then
if(f2.ShowDialog() == DialogResult.OK))
// User hits the OK button, refresh
else
// No refresh here...
Of course you don't need to handle yourself the closing process of the frmUpdate form. It is automatically handled by the Form engine
I have this code:
public partial class Form1 : Form
{
public Form1() { InitializeComponent(); }
private void button1_Click(object sender, EventArgs e)
{
FolderSelect("Please select:");
}
public static string FolderSelect(string txtPrompt)
{
// Now, we want to use the path information to population
// our folder selection initial location
string initialCheckoutPathDir = ("C:\\");
System.IO.DirectoryInfo info =
new System.IO.DirectoryInfo(initialCheckoutPathDir);
FolderBrowserDialog FolderSelect = new FolderBrowserDialog();
FolderSelect.SelectedPath = info.FullName;
FolderSelect.Description = txtPrompt;
FolderSelect.ShowNewFolderButton = true;
if (FolderSelect.ShowDialog() == DialogResult.OK)
{
string retPath = FolderSelect.SelectedPath;
if (retPath == null)
retPath = "";
DriveRecursion(retPath);
}
else
return "";
}
}
So i have a WindowsForm with a button. The user presses the button, and the FolderBrowserDialog appears. Once the user selects a drive, i want the form (with the button) to close as well.
I haven't been having any luck. Any ideas? Syntax would greatly be appreciated.
After the FolderSelect returns DialogResult.OK, you need to call this.close. So like this:
public string FolderSelect(string txtPrompt)
{
//Value to be returned
string result = string.empty;
//Now, we want to use the path information to population our folder selection initial location
string initialCheckoutPathDir = (#"C:\");
System.IO.DirectoryInfo info = new System.IO.DirectoryInfo(initialCheckoutPathDir);
FolderBrowserDialog FolderSelect = new FolderBrowserDialog();
FolderSelect.SelectedPath = info.FullName;
FolderSelect.Description = txtPrompt;
FolderSelect.ShowNewFolderButton = true;
if (FolderSelect.ShowDialog() == DialogResult.OK)
{
string retPath = FolderSelect.SelectedPath;
if (retPath == null)
{
retPath = "";
}
DriveRecursion(retPath);
result = retPath;
//Close this form.
this.Close();
}
return result;
}
Edit:
For some reason your FolderSelect method is static. You should remove the static so it has a reference to the form.
You can just call Close().
Additionally you can open your Form by using ShowDialog() instead of just Show() and set a DialogResult before closing it:
DialogResult = FolderSelect.ShowDialog();
Close();
EDIT:
And your FolderSelect method should be probably void. Better save the result of your FolderSelect dialog to a property.
Since FolderSelect is static, you won't have access to the form variables. So, you have two choices.
A) Make FolderSelect an instance method. Then you can just do this.Close() Mind you, the this is not necessary, I'm just putting it there for clarity.
B) Return a boolean from FolderSelect, and if it's true, inside the button click event, call this.Close()
After FolderSelect, put this.Close();