this is my problem: I have a main form where I have a panel that contains some buttons, when the user clicks a button a form is opened.( I have some buttons and clicking these buttons the user can open different forms )If the user click again the same button he can close the form.
this is what I do:
in the main form I have a method that is invoked when one of these buttons is clicked by the user, the method checks the text associated to the button in order to decide which is the button clicked. Once I have discovered which is the button that has been clicked it launches the form associated with the button.
this is the code
private void tlStBtn_Click(object sender, EventArgs e)
{
//// loop through all items in the ToolStrip
//foreach (Object item in toolStripMain.Items)
//{
// // if this item is a ToolStripButton object, check it
// if (item is ToolStripButton)
// {
// // cast the item to a ToolStripButton object and check it if the sender of the event is the currently looked at button in the loop
// ToolStripButton button = (ToolStripButton)item;
// button.Checked = (button == sender);
// }
//}
foreach (ToolStripItem item in this.VerticalToolBox.Items)
{
if ((item != sender) &&
(item is ToolStripButton))
{
((ToolStripButton)item).Checked = false;
}
}
if (sender_old != sender)
{
sender_old = sender;
if ((sender as ToolStripButton).Text == "Protection")
{
if (!Application.OpenForms.OfType<frm_Protection>().Any())
{
frm_Protection Newf = new frm_Protection(ref CurrentProject);
Newf.Show();
}
}
else
{
if (Application.OpenForms.OfType<frm_Protection>().Any())
{
Application.OpenForms.OfType<frm_Protection>().First().Close();
Properties.Settings.Default.Save();
}
GC.Collect();
GC.WaitForPendingFinalizers();
}
if ((sender as ToolStripButton).Text == "Info")
{
if (!Application.OpenForms.OfType<Frm_ObjectInfo>().Any())
{
Frm_ObjectInfo Newform = new Frm_ObjectInfo();
Newform.Show();
}
}
else
{
if (Application.OpenForms.OfType<Frm_ObjectInfo>().Any())
{
Application.OpenForms.OfType<Frm_ObjectInfo>().First().Close();
Properties.Settings.Default.Save();
}
GC.Collect();
GC.WaitForPendingFinalizers();
}
if ((sender as ToolStripButton).Text == "Layers")
{
if (!Application.OpenForms.OfType<Frm_LayersManage>().Any())
{
Frm_LayersManage Newform = new Frm_LayersManage();
Newform.Show();
Application.OpenForms.OfType<Frm_LayersManage>().First().UpdateLayers(null, CurrentProject.layers);
}
}
else
{
if (Application.OpenForms.OfType<Frm_LayersManage>().Any())
{
Application.OpenForms.OfType<Frm_LayersManage>().First().Close();
Properties.Settings.Default.Save();
UpdateScreen = true;
}
GC.Collect();
GC.WaitForPendingFinalizers();
}
if (Properties.Settings.Default.Grip2Enabled && (sender as ToolStripButton).Text == "Insert Grip")
{
gbx_SelectGrip.Visible = true;
}
else
{
gbx_SelectGrip.Visible = false;
}
//SelectedPoints.Clear();
//MousePointList.Clear();
//myIDs.Clear();
//IdxPointsEnt.Clear();
//RatiosLines.Clear();
//CadSource.cuts_tmp.Clear();
//IDAddedCutList.Clear();
//ZoomPort.SetValue(0, 0);
//ZoomPort.SetValue(0, 1);
//ZoomPort.SetValue(0, 2);
//ZoomPort.SetValue(0, 3);
//// Reset index of scrap selected by moving gripper
//idxScrap = -1;
//pnl_OpenTK.Refresh();
//// Se ho evidenziato uno SCRAP , annullo l'evidenziazione.
//if (IdsScrapDisablePath[0] != -1)
//{
// int identifiedScrap = CadSource.IdToIdx_Scrap(IdsScrapDisablePath[0]);
// if (CadSource.scraps[identifiedScrap].GripExists())
// {
// CadSource.scraps[identifiedScrap].Enabled = ScrapAbilitation.Enabled; // Disable clicked scrap
// }
// else
// {
// CadSource.scraps[identifiedScrap].Enabled = ScrapAbilitation.WithoutGrip; // Disable clicked scrap
// }
//}
//numScrap = 0;
//IdsScrapDisablePath = new List<int>() { -1, -1 };
}
else
{
(sender as ToolStripButton).Checked = false;
(sender as ToolStripButton).BackColor = Color.Transparent;
sender_old = new object() { };
if (Application.OpenForms.OfType<frm_Protection>().Any())
{
Application.OpenForms.OfType<frm_Protection>().First().Close();
Properties.Settings.Default.Save();
}
if (Application.OpenForms.OfType<Frm_ObjectInfo>().Any())
{
Application.OpenForms.OfType<Frm_ObjectInfo>().First().Close();
Properties.Settings.Default.Save();
}
if (Application.OpenForms.OfType<Frm_LayersManage>().Any())
{
Application.OpenForms.OfType<Frm_LayersManage>().First().Close();
Properties.Settings.Default.Save();
}
gbx_SelectGrip.Visible = false;
GC.Collect();
GC.WaitForPendingFinalizers();
}
SelectedPoints.Clear();
MousePointList.Clear();
myIDs.Clear();
IdxPointsEnt.Clear();
RatiosLines.Clear();
CurrentProject.cuts_tmp.Clear();
IDAddedCutList.Clear();
ZoomPort.SetValue(0, 0);
ZoomPort.SetValue(0, 1);
ZoomPort.SetValue(0, 2);
ZoomPort.SetValue(0, 3);
// Reset index of scrap selected by moving gripper
idxScrap = -1;
pnl_OpenTK.Refresh();
// Se ho evidenziato uno SCRAP , annullo l'evidenziazione.
if (IdsScrapDisablePath[0] != -1)
{
int identifiedScrap = CurrentProject.IdToIdx_Scrap(IdsScrapDisablePath[0]);
if (CurrentProject.scraps[identifiedScrap].GripExists())
{
CurrentProject.scraps[identifiedScrap].Enabled = ScrapAbilitation.Enabled; // Disable clicked scrap
}
else
{
CurrentProject.scraps[identifiedScrap].Enabled = ScrapAbilitation.WithoutGrip; // Disable clicked scrap
}
}
numScrap = 0;
IdsScrapDisablePath = new List<int>() { -1, -1 };
}
the forms that are opned clicking the buttons are forms where I have set the controlbox at false because I don't want that the user is able to close the forms without clicking again the button that has clicked to open it, but I have found a problem because if the user closes the form in this way (see the picture below) the status of the button remains checked but the form has been closed manually
To solve this problem I have thought to add this method associated to the event closing of my forms this is the code
private void frm_Protection_FormClosed(object sender, FormClosedEventArgs e)
{
////// if user closes manually the window without using the button I have to change the state of the button
Frm_Main f = new Frm_Main();
f = Application.OpenForms.OfType<Frm_Main>().Last();
f.tlsBut_Protection.Checked = false;
}
with this code if I close manually the form the status of the button it becomes false again in the main form
but I have discovered that It causes some problems to my program , one of this problem is that after closing the form if I click again the button it seems that the method associated to the clicking event is not called and the form is not opened I have to click it twice before it works again.
do you know why what do I do in the wrong way???
thanks for your help
To prevent a Form from closing, you can subscribe to the FormClosing event, which fires before the Form closes, and intercept (and cancel) the user's action.
private void frm_Protection_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
e.Cancel = true;
}
Unfortunately, clicking the "X" (in the Taskbar preview or in the program itself) and calling this.Close() are both treated as "UserClosing" close reasons, so we need to modify it slightly.
Add a property to frm_Protection, and use that to determine whether the Form can be closed:
public bool CanClose { private get; set; }
private void frm_Protection_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = !CanClose;
}
And then only set the property to true when you want to allow the Form to be closed:
var frmP = Application.OpenForms.OfType<frm_Protection>().FirstOrDefault();
if (frmP != null)
{
frmP.CanClose = true;
frmP.Close();
}
Related
StackOverflow may not be the correct place to as a why question, but I am looking for a because answer rather than a how to answer. I have already worked around the problem by disabling the handler in the hander.
The application has a DataGridView that displays inventory information during incoming inspection. The data grid is too wide for the screen and requires horizontal scrolling. To make the data easier to see and edit a modal editor has been added. There are 2 buttons to close the modal editor, either Save or Cancel. Using the close button at the top right corner of the modal editor form should perform the same action as the cancel button.
When the cancel button is clicked everything works fine. When the close button is clicked the modal editor FormClosed event fire twice. Why is the modal editor FormClosed event firing twice? Do I have a bug in my code?
private bool CancelModalEditor()
{
bool cancelled = false;
string cancelMsg = (_cancelClicked) ? "Canceling" : "Closing";
cancelMsg += " the editor will delete the Record with Serial Number: " + SerialNumber + " from the Audit Session. Is this what you want to do?";
DialogResult dlg = MessageBox.Show(cancelMsg, "", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (dlg == DialogResult.Yes)
{
SaveClicked = false;
}
else
{
cancelled = true;
}
return cancelled;
}
private void AEMEBtn_Cancel_Click(object sender, EventArgs e)
{
_cancelClicked = true;
if (!CancelModalEditor())
{
Close();
}
else
{
_cancelClicked = false;
}
}
private void AEModalEditor_FormClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (!_cancelClicked && !SaveClicked)
{
if (CancelModalEditor())
{
e.Cancel = true;
}
else
{
_cancelClicked = true; // Prevent Infite Loop
Close();
}
}
}
File where modal editor is invoked.
private void ModalEditorForm_Closed(object sender, FormClosedEventArgs e)
{
AEModalEditor modalEditor = (AEModalEditor)sender;
int currentRow = modalEditor.RowID - 1;
if (modalEditor.SaveClicked)
{
UpdateDataGridRowWithModalEditorValues(dgAssetDetails, currentRow, modalEditor.AssetControlsValues);
updateAuditDetailsDataGridRow(currentRow, modalEditor.AuditControlsValues);
UpdateAuditTextFields(modalEditor);
SelectAllCellsInRow(currentRow);
}
else
{
DeleteRowFromAllDataGridViews(modalEditor.SerialNumber, currentRow);
_previouslySelectedRow = -1;
}
// Save all records in either case so that session data isn't lost.
save(false);
_currentlySelectedDataGrid = DataGrids.None;
_modalEditorOpen = false;
txtSerialNumber.Focus();
}
Don't call close in the closing-event again. The form is already closing and don't need to be closed a second time.
private void AEModalEditor_FormClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (!_cancelClicked && !SaveClicked)
{
if (CancelModalEditor())
{
e.Cancel = true;
}
else
{
_cancelClicked = true;
// You called Close here again
Close();
}
}
}
i cant call or use event click of editor button that i create. the screen shot for the button is
the code that i make is like this
RepositoryItemComboBox repositoryItemComboBox1 = new RepositoryItemComboBox();
EditorButton lp = new EditorButton();
private void gridView1_CustomRowCellEdit(object sender, CustomRowCellEditEventArgs e)
{
repositoryItemComboBox1.Items.Clear();
GridView view = sender as GridView;
for (int i = 0; i < gridView1.RowCount; i++)
{
if (gridView1.GetDataRow(i) == null)
{
break;
}
string code = gridView1.GetDataRow(i)["code"].ToString();
if (!repositoryItemComboBox1.Items.Contains(code))
{
repositoryItemComboBox1.Items.Add(code);
}
}
if (e.Column.FieldName == "code" && view.IsFilterRow(e.RowHandle))
{
repositoryItemComboBox1.Buttons.Add(lp);
repositoryItemComboBox1.Buttons[0].Kind = DevExpress.XtraEditors.Controls.ButtonPredefines.Plus;
repositoryItemComboBox1.Buttons[1].Kind = DevExpress.XtraEditors.Controls.ButtonPredefines.Minus;
e.RepositoryItem = repositoryItemComboBox1;
}
when i click the minus nothing happen because no handler(event).
what i want is when i click that minus button it clear gridview filter
FYI : iam using devexpress
You can hook to the repositoryItem's ButtonClick event. In this event, you will know which button has been clicked. So let's say you create your button this way :
private void SomeMethod()
{
var buttonPlus = new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus);
var buttonMinus = new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Minus);
repositoryItemComboBox1.Buttons.Add(buttonPlus);
repositoryItemComboBox1.Buttons.Add(buttonMinus);
}
In the repositoryItemComboBox1_ButtonClick, you have access to the button properties in the "e" argument. In this example, i'm using the "Kind" property, but you could use the tag or anything really.
private void repositoryItemComboBox1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
{
if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Minus)
{
// do something
}
else if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)
{
// do something else
}
}
This is the way I do it.
I have a listbox with unnumbered items and a contexmenustrip. I wrote this code ( I know it seems too primitive, because of my inexpertness) It works fine but I have a little problem.
I want to make cms open at near your mouse position when you click on an item in listbox. and It will be opened at previous position when you click on blank. It is ok but cms is reopening by your each click. Is it posible to make it stay open when you click on blank not an item?
public Form1()
{
InitializeComponent();
}
int a, b, tx, ty;
int mx=0;
private void listBox1_MouseClick(object sender, MouseEventArgs e)
{
b = a;
a = listBox1.SelectedIndex;
if (listBox1.SelectedIndex != -1)
{
if (a!= b)
{
contextMenuStrip1.Show(MousePosition.X + 10, MousePosition.Y);
tx = MousePosition.X;
ty = MousePosition.Y;
mx =1;
}
else if (a==0 && b==0 && mx== 0)
{
tx = MousePosition.X;
ty = MousePosition.Y;
contextMenuStrip1.Show(tx + 10, ty);
mx = 1;
}
else
{
contextMenuStrip1.Show(tx + 10, ty);
}
}
}
Use AutoClose property of ContextMenuStrip to prevent it automatically closing.
ContextMenuStrip cms = new ContextMenuStrip();
cms.AutoClose = false;
Then call Close method to manually close it
cms.Close();
Or handle the Closing event of contextmenustrip and set e.Cancel = true based on your condition
void cms_Closing(object sender, ToolStripDropDownClosingEventArgs e)
{
if(your condition)
{
e.Cancel = true;
}
}
I am using .NET 3.5 with c# winforms. in this i am using MDI child tab control. it works fine if i open a form, it will open successfully. if i open same form again it opens. that means duplication of tabs.
My code is like below...
private void Main_MdiChildActivate(object sender, EventArgs e)
{
if (this.ActiveMdiChild == null)
tabForms.Visible = false; // If no any child form, hide tabControl
else
{
this.ActiveMdiChild.WindowState = FormWindowState.Maximized; // Child form always maximized
if (this.ActiveMdiChild.Tag == null)
{
TabPage tp = new TabPage(this.ActiveMdiChild.Text);
tp.Tag = this.ActiveMdiChild;
tp.Parent = tabForms;
tabForms.SelectedTab = tp;
this.ActiveMdiChild.Tag = tp;
this.ActiveMdiChild.FormClosed += new FormClosedEventHandler(ActiveMdiChild_FormClosed);
}
if (!tabForms.Visible) tabForms.Visible = true;
}
}
in this, every time this.ActiveMdiChild.Tag takes the value of null so it opens new form again and again. that means duplication of forms in tab control
Add the above method in order to check if the form with the name is as child in the mdi parent.
public static bool FormExist(string formName, out Form frm)
{
frm = null;
bool exist = false;
Form[] f = yourMdiParent.ActiveForm.MdiChildren;
foreach (Form ff in f)
{
if (ff.Name == formName)
{
frm = ff;
exist = true;
break;
}
}
return exist;
}
and add the check on adding the child form.
Form forma;
if(FormExist("yourchildformid",out forma) && forma !=null)
{
forma.Focus();
return;
}
I'm late to the party, but I use:
private void serviceManagerToolStripMenuItem_Click(object sender, EventArgs e)
{
// prevent duplicates
if (Application.OpenForms.OfType<ServiceManager>().FirstOrDefault() != null)
{
return;
}
ServiceManager serviceManager = new ServiceManager { MdiParent = this, WindowState = FormWindowState.Maximized };
serviceManager.Show();
}
I was able to get this to work with a few tweeks by combining other solutions
add this function to your Parent MDI Form
private bool checkTabExists(string tabVal)
{
foreach (TabPage tab in tabForms.TabPages)
{
if (tab.Text == tabVal)
return true;
}
return false;
}
Then Modify the original Form_MdiChildActivate to include an additional check
private void Main_MdiChildActivate(object sender, EventArgs e)
{
if (this.ActiveMdiChild == null)
tabForms.Visible = false; // If no any child form, hide tabControl
else
{
this.ActiveMdiChild.WindowState = FormWindowState.Maximized; // Child form always maximized
if(checkTabExists(this.ActiveMdiChild.Name))
{
//If the Child Form already Exists Go to it
foreach (TabPage tab in tabForms.TabPages)
{
if (tab.Text == this.ActiveMdiChild.Name)
tabForms.SelectedTab = tab;
}
}
// If child form is new and has no tabPage, create new tabPage
else if (this.ActiveMdiChild.Tag == null)
{
ActiveMdiChild.TopLevel = false;
ActiveMdiChild.Dock = DockStyle.Fill;
ActiveMdiChild.FormBorderStyle = FormBorderStyle.None;
// Add a tabPage to tabControl with child form caption
TabPage tp = new TabPage(this.ActiveMdiChild.Text);
tp.Tag = this.ActiveMdiChild;
tp.Parent = tabForms;
tabForms.SelectedTab = tp;
this.ActiveMdiChild.Tag = tp;
this.ActiveMdiChild.FormClosed += new FormClosedEventHandler(Main_FormClosed);
}
if (!tabForms.Visible) tabForms.Visible = true;
//tabForms.AutoSize = true;
//tabForms.TabPages[0].Height = 38;
}
}
I am having a form which will be shown on leaving the control of the previous form. Suppose my form1 have a textbox i will enter a value as 2 there immediately after leaving i will show form2 there i will have some textboxes out of them i will have a sequence number which should be autoincremented like if i have 0001 in that on initial load after clicking save i will show the same form untill it matches the previous value what i need is when the user clicks on save i would like to auto increment the textbox value can any one give me an idea
My code is as follows
Form2 save button
private void btnSave_Click(object sender, EventArgs e)
{
if (filecontrolvariables.m_Addendaclick == true)
{
objCTXAddenda.Addenda_RecordTypeCode = txtRectypecode.Text;
objCTXAddenda.Addendatypecode = txtAddendaTypeCode.Text;
objCTXAddenda.PaymentRelatedInformation = txtPaymentRelInfo.Text;
objCTXAddenda.Addendasequencenumber = txtAddendaSeqNo.Text;
objCTXAddenda.EntryDetailSequenceNumber = txtEntryDetailSeqNumber.Text;
Append.addendawithentry++;
objCTXAddenda.saveAddenda(Append.FileName);
this.Close();
frmMain.loadAddenda("Addenda", true);
}
else
{
timeBeforeClose--;
if (timeBeforeClose == 0)
{
txtAddendaSeqNo.Text = Append.AddendaSequenceno.ToString("0000");
objCTXAddenda.Addenda_RecordTypeCode = txtRectypecode.Text;
objCTXAddenda.Addendatypecode = txtAddendaTypeCode.Text;
objCTXAddenda.PaymentRelatedInformation = txtPaymentRelInfo.Text;
objCTXAddenda.Addendasequencenumber = txtAddendaSeqNo.Text;
objCTXAddenda.EntryDetailSequenceNumber = txtEntryDetailSeqNumber.Text;
objCTXAddenda.saveAddenda(Append.FileName);
txtPaymentRelInfo.Text = string.Empty;
this.Close();// I will close the form when this matches
Append.addendawithentry++;
}
else
{
objCTXAddenda.Addenda_RecordTypeCode = txtRectypecode.Text;
objCTXAddenda.Addendatypecode = txtAddendaTypeCode.Text;
objCTXAddenda.PaymentRelatedInformation = txtPaymentRelInfo.Text;
objCTXAddenda.Addendasequencenumber = txtAddendaSeqNo.Text;
objCTXAddenda.EntryDetailSequenceNumber = txtEntryDetailSeqNumber.Text;
objCTXAddenda.saveAddenda(Append.FileName);
txtPaymentRelInfo.Text = string.Empty;
Append.addendawithentry++;
Append.AddendaSequenceno++;
}
}
}
When form loads but for the second time as it is not loading i can not increment
private void frmAddenda_Load(object sender, EventArgs e)
{
Append.addendawithentry = 0;
if (filecontrolvariables.m_Addendaclick == true)
{
btnCancel.Visible = true;
Append.AddendaSequenceno++;
StringBuilder sbEmpty = new StringBuilder();
Append.sbEntryAddenda = sbEmpty;
txtRectypecode.Text = ((char)55).ToString();
txtAddendaTypeCode.Text = "05";
txtAddendaSeqNo.Text = Append.AddendaSequenceno.ToString("0000");
}
else
{
btnCancel.Visible = false;
Append.AddendaSequenceno++;
StringBuilder sbEmpty = new StringBuilder();
Append.sbEntryAddenda = sbEmpty;
txtRectypecode.Text = ((char)55).ToString();
txtAddendaTypeCode.Text = "05";
if (!(timeBeforeClose == 0))
txtAddendaSeqNo.Text = Append.AddendaSequenceno.ToString("0000");
else
txtAddendaSeqNo.Text = Append.AddendaSequenceno.ToString("0000");
}
}
Prev form code
private void txtNoOfAddenda_Leave(object sender, EventArgs e)
{
filecontrolvariables.m_Addendaclick = false;
pass();
if (Convert.ToInt16(txtNoOfAddenda.Text) == Convert.ToInt16(((char)48).ToString()))
{
txtAddendarecord.Text = ((char)48).ToString();
}
else
txtAddendarecord.Text = ((char)49).ToString();
}
private void pass()
{
string traceNo = string.Empty;
i = 0;
if (!int.TryParse(txtNoOfAddenda.Text, out i))
{
MessageBox.Show("Enter numeric value betewwn(0-9999)");
txtNoOfAddenda.Focus();
}
else
{
if (i > 0)
{
traceNo = txtTraceNo.Text.Substring(8, 7);
frmAddenda frmAddenda = new frmAddenda(i, traceNo);
frmAddenda.ShowDialog();
txtNoOfAddenda.Leave -= txtNoOfAddenda_Leave;
}
}
}
i am not able to understand your problem completely but wants to suggest you on what i understood.
what i understand is that you wants to increment value of your textbox of form1 on click of form2's save button.
to do so follow below steps:
make that textbox of form1 to public in which you wants value from form1.
create an object of form1 in form2 like:
Form1 f1;
now when you shows form2 on lostfocus from your form1's textbox. before showing form2 do following:
Form2 f2 = new Form2();
f2.f1 = this;
f2.showdialog() or you can use f2.show();
now in form2 on click of save button write below code:
f1.yourPublicTextBox.text = "any value which you wants on textbox";
or as you said you wants to autoincrement it then
f1.yourPublicTextBox.text = (Convert.ToInt32(yourPublicTextBox.text) + 1).toString();
and its done..
EDIT:
do not let the form2 close because on close of form2 your object of form2 will become null. so just hide it and show it again.
so below code is showing that on click of close button we are not let user allowing to close form we are just hiding it and you can show it again when ever it required.
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
this.Hide();
}