C# Windows Forms switching -
i got form1
, creates form when button clicked:
private void toolstripmenuitem_click(object sender, eventargs e) { form f5 = new form5(); f5.show(); }
when happens, need determine if form f5 exists,so if exists,when button pressed,it switches existing form instead of making new one.if doesn't exist,then has create new form. how do this,if can't check whether objects exist or not until declare them? how check f5 existence before declare it,so can create when there no such form , needed?
the correct way of doing maintain reference form5
object when create it. can by, example, declaring class-level variable.
public class myform : form { private form5 m_frm5 = null; // ...other code... private void toolstripmenuitem_click(object sender, eventargs e) { if (m_frm5 == null) { m_frm5 = new form5(); } m_frm5.show(); } }
obviously need choose scope appropriately, depending on need access form object. static
local variable might work equally well, or might need make global entire application.
alternatively, can iterate through application.openforms
collection, checking see if instance of form5
has been created.
private void toolstripmenuitem_click(object sender, eventargs e) { foreach (form f in application.openforms) { if (f.gettype() == typeof(form5)) { f.show(); return; } } form5 frm5 = new form5(); frm5.show(); }
pro tip: choose more descriptive names form class defaults. form5 tells me nothing.
Comments
Post a Comment