Forms opens two times - c#

In the code below, I open a form with frmContact.ShowDialog(); and then when I close the form by clicking on the OK button in the form it closes, but then it opens again because I have the frmContact.ShowDialog() in the if statement. Could this be done in some oterh way?
// Button add new customer
private void btnAdd_Click(object sender, EventArgs e)
{
ContactForm frmContact = new ContactForm();
frmContact.ShowDialog(); // Show the contact form window
if (frmContact.ShowDialog() == DialogResult.OK)
{
MessageBox.Show("OK", "Test", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}

Simply remove the first call:
ContactForm frmContact = new ContactForm();
if (frmContact.ShowDialog() == DialogResult.OK)
{
MessageBox.Show("OK", "Test", ...);
}
Another option (especially useful if the code that shows the form is not next to the code that checks the return value) is to use Form.DialogResult:
ContactForm frmContact = new ContactForm();
frmContact.ShowDialog();
if (frmContact.DialogResult == DialogResult.OK)
{
MessageBox.Show("OK", "Test", ...);
}

Just get rid of the first ShowDialog.

Just leave the second if, like this:
private void btnAdd_Click(object sender, EventArgs e)
{
ContactForm frmContact = new ContactForm();
if (frmContact.ShowDialog() == DialogResult.OK) //just one call
{
MessageBox.Show("OK", "Test", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}

private void btnAdd_Click(object sender, EventArgs e)
{
ContactForm frmContact = new ContactForm();
frmContact.ShowDialog();
}

Related

Hide and Close is not working in all my form

I have a label with a text "X" and I use this to close my forms. I have this code in my login:
private void btnLogIn_Click(object sender, EventArgs e)
{
if (userLevel.IndexOf("ADMIN") + 1 > 0)
{
Save_Data();
using (AdminGateOpt adminOptions = new AdminGateOpt())
{
adminOptions.gUsers = User;
adminOptions.windowNumber = windowNumber;
adminOptions.userDetails = userLevel.Split('|');
adminOptions.ShowDialog();
Close();
}
}
}
..and if the userlevel is an admin, then it will go to another form:
private void btnInGate_Click(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Do you want to go in In-Gate Form?", String.Empty, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dialogResult == DialogResult.Yes)
{
ReadBarCodeInGate gateForm = new ReadBarCodeInGate();
gateForm.gUsers = gUsers;
gateForm.windowNumber = windowNumber;
gateForm.userDetails = userDetails;
gateForm.ShowDialog();
Hide();
}
}
private void buttonExit_Click(object sender, EventArgs e)
{
login Login = new login();
Login.ShowDialog();
Hide();
}
And it's also the same to other forms that suddenly it became like this, that once I hit the X label button it will go to another form but it wont close nor hide the previous form/s.

Deleteing rows from DataGridView with custom DialogBox

What i have done is a user rightclicks on a row. A menu appears, they choose the delete option. But there is no confirmation dialog. How can I use a custom form that i have created. that has delete,cancel buttons.
My Code that works;
private void Delete_Click(object sender, EventArgs e)
{
if (this.dgvTable.SelectedRows.Count > 0)
{
dgvTable.Rows.RemoveAt(this.dgvTable.SelectedRows[0].Index);
}
//Call FrmDelete??
}
How can I use the new form, to confirm the delete. I have tried using a MessageBox
DialogResult dialogResult = MessageBox.Show("ARE YOU SURE?", "DELETE Title", MessageBoxButtons.YesNo);
if(dialogResult == DialogResult.Yes)
{
if (this.dgvTable.SelectedRows.Count > 0)
{
dgvTable.Rows.RemoveAt(this.dgvTable.SelectedRows[0].Index);
}
}
else if (dialogResult == DialogResult.No)
{
//do something else
}
I know thats probably the easiest option. but I would like to use the new Delete Form.
Thanks
You have to use the DialogResult property of your new form.
In your new form:
void ButtonDelete_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.OK;
this.Close();
}
void ButtonCancel_Click(object sender, EventArgs e)
{
this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.Close();
}
Then in the main form:
private void Delete_Click(object sender, EventArgs e)
{
YourDialog dlg = new YourDialog();
DialogResult dialogResult = dlg.ShowDialog();
if(dialogResult == DialogResult.OK)
{
if (this.dgvTable.SelectedRows.Count > 0)
{
dgvTable.Rows.RemoveAt(this.dgvTable.SelectedRows[0].Index);
}
}
else if (dialogResult == DialogResult.Cancel)
{
return;
}
}
You just have to change a few lines.
The first to show the form:
DialogResult dialogResult = new DeleteForm().ShowDialog();
And then check the result is "OK" rather than "Yes":
if(dialogResult == DialogResult.OK)
Finally, DialogResult.No will never be returned, so your else if should just be else.

how to call MdiChild from MDIParent form

I create a new MdiChild from MainForm using this method:
AdminLogInForm adminForm;
private void LogInAsAdminMenuItem_Click(object sender, EventArgs e)
{
if (adminForm == null)
{
adminForm = new AdminLogInForm();
adminForm.MdiParent = this;
adminForm.Show();
adminForm.Dock = DockStyle.Fill;
adminForm.BringToFront();
LogInAsAdminMenuItem.Enabled = false;
}
else
{
adminForm.Activate();
adminForm.BringToFront();
}
}
Why when i close my child, using in chld form "this.close()" using that method i cant open it anymore?
there i call close();
private void cancelLogInButton_Click(object sender, EventArgs e)
{
this.MdiParent.Activate();
if(this.MdiParent!=null)
((MainForm)this.MdiParent).LogInAsAdminMenuItem.Enabled = true;
this.Close();
}
by the way to make work that I asked before I hed to plase this.Close(); after all statements .
By closing the form you are not making adminForm instance to null (Which is what your if condition will check when you try to open it next time.)
On diposal of your form make adminForm = null and then your if condition will work next time.
private void LogInAsAdminMenuItem_Click(object sender, EventArgs e)
{
if (adminForm == null)
{
adminForm = new AdminLogInForm(this);
adminForm.Disposed += new EventHandler(adminForm_Disposed); //Add Disposed EventHandler
adminForm.MdiParent = this;
adminForm.Show();
adminForm.Dock = DockStyle.Fill;
adminForm.BringToFront();
LogInAsAdminMenuItem.Enabled = false;
}
else
{
adminForm.Activate();
adminForm.BringToFront();
}
}
void adminForm_Disposed(object sender, EventArgs e)
{
adminForm = null;
}
As Described by Marshal that the closing of a form makes it disposed you should add a condition for disposing as well like this
AdminLogInForm adminForm;
private void LogInAsAdminMenuItem_Click(object sender, EventArgs e)
{
if (adminForm == null || adminForm.IsDisposed)
{
adminForm = new AdminLogInForm();
adminForm.MdiParent = this;
adminForm.Show();
adminForm.Dock = DockStyle.Fill;
adminForm.BringToFront();
LogInAsAdminMenuItem.Enabled = false;
}
else
{
adminForm.Activate();
adminForm.BringToFront();
}
}
Or you can also create a function to use a form as mdi
like this

How to check in real time if data was enteder from one of the classes into a texbox?

My question comes from a problem which I have right now. I have MainWindow, AuthenticateWindow, and AddEntryWindow which all are WinForms. In main window I have possibility to Authenticate and Add Entry into my main windows textbox. They can not add an entry until they authenticate (no problem with this). I need to add an entry to the text box which will update my main windows textbox. The problem if, how can I check if entry was added to my textbox?
I am trying to have a Save option from menu strip. I am getting an error whenever I am trying to save an empty file. How could I authenticate the saving process by Save button by having it first disabled, and enabled after entry was added?
I could always verify if if textbox had an entry but I want to have button disabled first, and enabled after entry was added. I do not have a privilege to do so as of right now.
Please ask questions if I am not clear enough.
private void tsmiSave_Click(object sender, EventArgs e)
{
// Open sfdSaveToLocation which let us choose the
// location where we want to save the file.
if (txtDisplay.Text != string.Empty)
{
sfdSaveToLocation.ShowDialog();
}
}
MainWindow.cs
using System;
using System.IO;
using System.Windows.Forms;
namespace Store_Passwords_and_Serial_Codes
{
public partial class MainWindow : Form
{
private AuthenticateUser storedAuth;
public MainWindow()
{
InitializeComponent();
}
private void MainWindow_Load(object sender, EventArgs e)
{
// Prohibit editing.
txtDisplay.Enabled = false;
}
public string ChangeTextBox
{
get
{
return this.txtDisplay.Text;
}
set
{
this.txtDisplay.Text = value;
}
}
private void tsmiAuthenticate_Click(object sender, EventArgs e)
{
AuthenticationWindow authWindow = new AuthenticationWindow();
authWindow.ShowDialog();
storedAuth = authWindow.Result;
}
private void tsmiAddEntry_Click(object sender, EventArgs e)
{
if (storedAuth == null)
{
DialogResult result = MessageBox.Show
("You must log in before you add an entry."
+ Environment.NewLine + "You want to authenticate?",
"Information", MessageBoxButtons.YesNo,
MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
AuthenticationWindow authWindow =
new AuthenticationWindow();
authWindow.ShowDialog();
storedAuth = authWindow.Result;
AddEntryWindow addWindow = new AddEntryWindow
(this, storedAuth.UserName, storedAuth.Password);
addWindow.ShowDialog();
}
}
else
{
AddEntryWindow addWindow = new AddEntryWindow
(this, storedAuth.UserName, storedAuth.Password);
addWindow.ShowDialog();
}
}
private void tsmiClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void tsmiSave_Click(object sender, EventArgs e)
{
// Open sfdSaveToLocation which let us choose the
// location where we want to save the file.
sfdSaveToLocation.ShowDialog();
}
private void sfdSaveToLocation_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
string theFileName = sfdSaveToLocation.FileName;
EncryptDecrypt en = new EncryptDecrypt();
string encrypted = en.Encrypt(txtDisplay.Text,
storedAuth.UserName, storedAuth.Password);
MessageBox.Show(encrypted);
File.WriteAllText(theFileName, encrypted);
}
}
}
AddEntryWindow.cs
using System;
using System.Windows.Forms;
// Needed to be used with StringBuilder
using System.Text;
// Needed to be used with ArrayList.
using System.Collections;
namespace Store_Passwords_and_Serial_Codes
{
public partial class AddEntryWindow : Form
{
string user, pass;
// Initializind ArrayList to store all data needed to be added or retrived.
private ArrayList addedEntry = new ArrayList();
// Initializing MainWindow form.
MainWindow mainWindow;
// Default constructor to initialize the form.
public AddEntryWindow()
{
InitializeComponent();
}
public AddEntryWindow(MainWindow viaParameter, string user, string pass)
: this()
{
mainWindow = viaParameter;
this.user = user;
this.pass = pass;
}
private void AddEntryWindow_Load(object sender, EventArgs e)
{ }
private void btnAddEntry_Click(object sender, EventArgs e)
{
// Making sure that type is selected.
if (cmbType.SelectedIndex == -1)
{
MessageBox.Show("Please select entry type!", "Error!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
// Each field must be filled for specified type.
// Here we are checking if all fields were filled.
else if ((cmbType.SelectedIndex == 0 && (txtUserName.Text == string.Empty || txtPassword.Text == string.Empty)) ||
(cmbType.SelectedIndex == 1 && (txtURL.Text == string.Empty || txtPassword.Text == string.Empty)) ||
(cmbType.SelectedIndex == 2 && (txtSoftwareName.Text == string.Empty || txtSerialCode.Text == string.Empty)))
{
MessageBox.Show("Please fill all the fields!", "Error!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
int totalEntries = 0;
if(cmbType.SelectedIndex == 0)
addedEntry.Add(new AddPC(cmbType.Text,
txtUserName.Text, txtPassword.Text));
else if(cmbType.SelectedIndex == 1)
addedEntry.Add(new AddWebSite(cmbType.Text,
txtUserName.Text, txtPassword.Text, txtURL.Text));
else if(cmbType.SelectedIndex == 2)
addedEntry.Add(new AddSerialCode(cmbType.Text,
txtSoftwareName.Text, txtSerialCode.Text));
StringBuilder stringBuilder = new StringBuilder();
foreach (var list in addedEntry)
{
if (list is AddPC)
{
totalEntries++;
AddPC tmp = (AddPC)list;
stringBuilder.Append(tmp.ToString());
}
else if (list is AddWebSite)
{
totalEntries++;
AddWebSite tmp = (AddWebSite)list;
stringBuilder.Append(tmp.ToString());
}
else if (list is AddSerialCode)
{
totalEntries++;
AddSerialCode tmp = (AddSerialCode)list;
stringBuilder.Append(tmp.ToString());
}
}
mainWindow.ChangeTextBox = stringBuilder.ToString();
mainWindow.tsslStatus.Text = "A total of " + totalEntries + " entries added.";
// Clearing all fields.
ClearFields();
}
}
private void btnClear_Click(object sender, EventArgs e)
{
ClearFields();
}
private void btnClose_Click(object sender, EventArgs e)
{
// Closing the Add Entry Window form.
this.Close();
}
private void cmbType_SelectedIndexChanged(object sender, EventArgs e)
{
// Deciding which data must be entered depending on
// what type is selected from combo box.
// PC
if (cmbType.SelectedIndex == 0)
{}
// Web Site
else if (cmbType.SelectedIndex == 1)
{}
// Serial Code
else if (cmbType.SelectedIndex == 2)
{}
}
private void ClearFields()
{
// Clearing all fields to the default state.
}
}
}
Regards.
It sounds like you probably just want to subscribe to the TextChanged event, which will be fired whenever the text in the textbox changes.
I can't say I really followed everything that you're doing, but I think you should be fine to just enable or disable your Save button within that event handler.
EDIT: It's not really clear where all your different components live, but you want something like:
// Put this after the InitializeComponent() call in the constructor.
txtDisplay.TextChanged += HandleTextBoxTextChanged;
...
private void HandleTextBoxTextChanged(object sender, EventArgs e)
{
bool gotText = txtDisplay.Text.Length > 0;
menuSaveButton.Enabled = gotText;
}
I'd also strongly advise you not to use ArrayList but to use the generic List<T> type. The non-generic collections should almost never be used in new code.

Validation in modal form

I have a simple modal form in which I have to check user entered data. But after validation the form gets closed. It behaves like this because of not empty DialogResult property but I need this value for other purposes (in a parent form)
Any ideas?
A little code to clear things up
//This method creates and calls a modal form.
public static Definition edit(Definition w)
{
EditForm ed = new EditForm();
DialogResult dr = ed.ShowDialog();
if (dr == DialogResult.OK)
{
//update some fields of passed object
}
//other code
}
private void btnSave_Click(object sender, EventArgs e)
{
if (validateForm())
{
DialogResult = DialogResult.Yes;
Close();
}
}
I would do it this way:
private void btnSave_Click(object sender, EventArgs e)
{
if (validateForm())
{
DialogResult = DialogResult.Yes;
Close();
}
else
{
DialogResult = DialogResult.None;
}
}
I.e. as you said, clear the DialogResult.
Add a FormClosing event handler and then if the validation fails set e.Cancel = true:
private void EditForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (this.DialogResult == DialogResult.OK)
{
e.Cancel = !ValidateInput();
}
}
This will leave you sub form open and let the user correct the mistakes. You can check whether the "OK" or "Cancel"/Window Close button has been clicked by checking the DialogResult and only performing the validation if it's OK.

Categories