need to unify child form button clicks into one routine - c#

I have discovered that I am beginning to use the same code for a few different click events. I have a MDI form and there are "master children" as I call them that will open other children associated with the master. This is the master/detail thing going on. An example is the Company master child will have buttons to open the Contact, Industry, etc associated with the Company. Below is a sample of the code that opens the Contact child form. This code is also being used for the others as well.
What I am looking to do is to be able to use just one and fill in the button, form, message, and a connection label between Company and Contact. The code at the botton is what I have so far and I marked the lines that need to be changed with what I'm looking for. The lines with the single arrow "seem" to work but the multi arrow line can't get it right. Providing both for comparison reasons.
Could someone look this/these over and see what I'm doing wrong (or missing) in the consolidated code?
Thanks...John
//CODE TO OPEN THE CONTACT CHILD FORM
private void btnCompanyContact_Click(object sender, EventArgs e)
{
bool isOpen = false;
foreach (Form f in Application.OpenForms)
{
if (f is frmContact)
{
isOpen = true;
MessageBox.Show("The Contact list is already open.", "INFORMATION", MessageBoxButtons.OK);
f.BringToFront();
f.Controls["lblRecordID"].Text = lblCompanyID.Text;
break;
}
}
if (!isOpen)
{
frmContact contact = new frmContact();
contact.MdiParent = this.MdiParent;
contact.ReceiveValue(lblCompanyID.Text);
contact.StartPosition = FormStartPosition.Manual;
contact.Location = new Point(100, 100);
contact.Show();
}
else
{
//do nothing
}
}
//CONSOLIDATE ALL THE BUTTON OPENING INTO THIS ROUTINE
private void OpenCompanyInformationForm(Button btn, Form name, string message, string lbl)
{
bool isOpen = false;
foreach (Form f in Application.OpenForms)
{
-> if (f == name)
{
isOpen = true;
-> MessageBox.Show("The " + message + " list is already open.", "INFORMATION", MessageBoxButtons.OK);
f.BringToFront();
-> f.Controls[lbl].Text = lblCompanyID.Text;
break;
}
}
if (!isOpen)
{
->->-> frmContact contact = new frmContact();
contact.MdiParent = this.MdiParent;
contact.ReceiveValue(lblCompanyID.Text);
contact.StartPosition = FormStartPosition.Manual;
contact.Location = new Point(100, 100);
contact.Show();
}
else
{
//do nothing
}
}

To perfom the custom function ReceiveValue you need to create a derived class from Form
and create all you forms from this derived class
public class ContactBase : Form
{
public void ReceiveValue(string p_Value)
{
Button button = (Button)this.Controls["lblRecordID"];
if (button == null) return;
button.Text = p_Value;
}
}
private void OpenCompanyInformationForm(Form name)
{
bool isOpen = false;
foreach (Form f in Application.OpenForms)
{
// Just to compare, you can use the Name property
-> if (f.Name == name.Name)
{
isOpen = true;
// If the message is just a name of form, you can use Name or Text property
// in this case you can supress message param
-> MessageBox.Show("The " + f.Text + " list is already open.", "INFORMATION", MessageBoxButtons.OK);
f.BringToFront();
// If the ReceiveValue is just to pass the text of lblCompanyID for lblRecordID button, you can use the function here
-> ((ContactBase)name).ReceiveValue(lblCompanyID.Text);
break;
}
}
if (!isOpen)
{
->->-> ContactBase contact = (ContactBase)Activator.CreateInstance(name.GetType());
contact.MdiParent = this.MdiParent;
contact.ReceiveValue(lblCompanyID.Text);
contact.StartPosition = FormStartPosition.Manual;
contact.Location = new Point(100, 100);
contact.Show();
}
else
{
//do nothing
}
}

Related

Form doesn't show up in excel on ribbon button press after publishing

The form shows up fine when pressing the button in debug and after publish in the user the project is in, but on a different user the form doesn't show up.
public partial class Ribbon1
{
private void newIron_Click(object sender, RibbonControlEventArgs e)
{
IronForm form = new IronForm();
form.Visible();
}
}
public partial class IronForm : Form
{
public IronForm()
{
InitializeComponent();
this.FormBorderStyle = FormBorderStyle.FixedSingle; // makes form non resizeable
}
// path - photo path
public void ChangeUC(string uc, string path = "")
{
if (uc == "ms")
{
string image = path;
this.measurements1.pictureBox1.Load(Path.Combine(Globals.ThisAddIn.path + #"\lengths", path + ".png"));
this.measurements1.sketchPath = Path.Combine(Globals.ThisAddIn.path, path + ".png");
string[] data = File.ReadAllLines(Globals.ThisAddIn.path + #"\sides.cfg");
foreach (string line in data)
{
if (line.Split('-')[0] == image)
{
this.measurements1.sides = int.Parse(line.Split('-')[1]);
break;
}
}
// shows textbox for the amount of sides
if (this.measurements1.sides > 0)
{
for (int i = 1; i <= this.measurements1.sides; i++)
{
this.measurements1.entries[i].Visible = true;
this.measurements1.labelsEntries[i].Visible = true;
}
this.measurements1.Visible = true;
}
else
{
MessageBox.Show("sides error");
this.sketches1.Visible = true;
}
}
else if (uc == "sk")
{
this.sketches1.Visible = true;
}
}
}
I've tried changing form.Visible to form.Show and form.ShowDialog but that didn't do anything.
I tried to publish a simple form and it worked fine. Showing a MessageBox works fine.
Anybody know what I need to do?

C# raise event in Child Form Called From Parent Form

I have a tool strip menu in my parent form and I'm loading my child forms into a panel as user controls. I need to fire an event in my child form when the user clicks on the menu strip in my parent form.
Here is the event in the parent control:
//Character Name
private void randomNameToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
if (_SQL_Settings.TabControl == "Character Builder")
{
}
else
{
MessageBox.Show("You must be in the Character Builder Screen
To Generate A Random Character Name, Please Try Again.");
}
}
catch(Exception ex)
{
}
}
//Character
private void randToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
if (_SQL_Settings.TabControl == "Character Builder")
{
}
else
{
MessageBox.Show("You must be in the Character Builder Screen
To Generate A Random Character, Please Try Again.");
}
}
catch (Exception ex)
{
}
}
Here is where I Build my child form in the Parent form:
case "Character Builder":
{
Character_Builder CC = new Character_Builder();
panCC.Controls.Clear();
CC.Dock = DockStyle.Fill;
panCC.Controls.Add(CC);
CC.Main_Menu += Main_Menu;
break;
}
And here is the functions I want to fire off when the user clicks on the parent form menu strip items
private void Generate_Raondom_Character()
{
try
{
}
catch(Exception ex)
{
}
}
private void Generate_Random_Character_Name()
{
try
{
}
catch (Exception ex)
{
}
}
I have added these two events in my child form but I think they need to be in my parent form.
Events:
public event EventHandler Random_Character;
public event EventHandler Random_Name;
Does anyone know what I need to do to get this to work? Sample would be great. I know how to do it in Vb just not c#.
I have one solution. This is not what I wanted to do but it seems to work. I am looping through the controls in my child forum until I find the control I want and editing the controls text. I wanted to use events but I guess this works too. If anyone has better ways to do this please share:
if (_SQL_Settings.TabControl == "Character Builder")
{
DataTable dt = new DataTable();
dt = _SQL.Random_Character_Name();
foreach (Control Parentctrl in panCC.Controls)
{
if (Parentctrl.Name == "Character_Builder")
{
foreach (Control Childctrl in Parentctrl.Controls)
{
if (Childctrl.Name == "cbFirstName")
{
Childctrl.Text = dt.Rows[0]["First_Name"].ToString();
}
if (Childctrl.Name == "cbLastName")
{
Childctrl.Text = dt.Rows[0]["Last_Name"].ToString();
}
if (Childctrl.Name == "cbCharacterTitle")
{
Childctrl.Text = dt.Rows[0]["Character_Title"].ToString();
}
}
}
}

How to close an activeMidForm and open another?

I have a method that I use the open a Mid Child.
Lets say I am on a form called "InventoryAdd" on this form I have a drop down menu. When a user selects a value "-1" from the menu, I want to open another (ie. DepartmentsAdd().) Then after DepartmentAdd open I want to close InventoryAdd form.
this is the code behind the menu on InventoryAdd form
private void InputDepartment_SelectedValueChanged(object sender, EventArgs e) {
//InputDepartment.ValueMember = "ID";
int selectedDept = Convert.ToInt32(InputDepartment.SelectedValue);
if (selectedDept == -1) {
Form myForm = this.ActiveMdiChild;
Common.OpenMyForm("Vendors", new string[] { "add" }, new DepartmentsAdd());
if (myForm != null) {
myForm.Close();
}
}
}
This method what opens the new Mid form
public static void OpenMyForm(string sectionName, string[] keys, Form myform) {
//make sure there are no other forms of the ame type open
foreach (Form form in Application.OpenForms) {
if (form.GetType() == myform.GetType()) {
form.Activate();
return;
}
}
if (Settings._AuthenticationMode == "Thumbprint") {
var newMDIChild = myform;
// Set the Parent Form of the Child window.
newMDIChild.MdiParent = AppContext.CurrentContext.MainForm;
// Display the new form.
newMDIChild.Show();
}
if (Settings._AuthenticationMode == "Single" && UserInfo.Autherized == true) {
var role = new Roles();
if (role.hasAccess(sectionName, keys)) {
var newMDIChild = myform;
// Set the Parent Form of the Child window.
newMDIChild.MdiParent = AppContext.CurrentContext.MainForm;
// Display the new form.
newMDIChild.Show();
}
else {
Common.Alert("You do not have a permissions to perform this action!");
}
}
}
}
My code open the Mid form with no issues. However, the "InventoryAdd" form never close. "myForm" is always null to it never close it.
How can I properly close the Mid form?
Thanks
If you set an event listener for shown on the newly opened form in the calling context you can have the existing form close itself once its child is opened.
Form myForm=new Form();
myForm.shown += closeForm;
...
void closeForm(object sender, EventArgs e){
this.Dispose(); // as long as within the previous forms context.
}
myForm.Close();
is closing the program try to use
myForm.Hide();

Must I remove a form assigned to a TabPage and then add a new one, or can I access the existing one to change values it contains dynamically?

I am dynamically assigning forms to tab pages. It works fine, except when I try to assign
an updated version of the form (with different text values assigned to the controls) to the tab page. I am actually a little surprised that it doesn't crash when I create multiple instances of the form and assign them to the tab page (if the new ones are just stacking on top of the older ones, you would think the new one would be on top and the new values are visible).
So...what do I need to do to remove the previous form I added to the tab page before adding the new version? Or can I access the existing form and change its values.
I guess it would be clearer if I just showed the code:
Main form:
private enum TabControls {
BasicInfo,
ConfidentialInfo,
RolesAndSecurity,
InactiveInfo
}
string currentNode = string.Empty;
public Form1() {
InitializeComponent();
CenterToScreen();
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) {
currentNode = e.Node.Name;
UpdateActiveTabForNode();
}
// This is called both by treeView1_AfterSelect (sic, I changed the name to
// treeViewSearchWorker) and by tabControlWorker_SelectedIndexChanged().
// currentNode is set/overwritten on clicking a node and saved in a form var.
// The active tab page is always known via the TabControl's SelectedIndex
// property, so there is no need to pass in either value.
private void UpdateActiveTabForNode() {
int ActiveTabPage = tabControlWorker.SelectedIndex;
switch (ActiveTabPage) {
case (int)TabControls.BasicInfo:
if (tabPageBasicInfo.Controls.Count > 0) {
;// tabPageBasicInfo.Controls.Remove(0);<-- What to pass in here?
}
BasicInfoPseudoTab bipt = new BasicInfoPseudoTab(currentNode);
tabPageBasicInfo.Controls.Add(bipt);
tabPageBasicInfo.BringToFront();
bipt.Show();
break;
case (int)TabControls.ConfidentialInfo:
ConfidentialInfoPseudoTab cipt = new ConfidentialInfoPseudoTab(currentNode);
tabPageConfidentialInfo.Controls.Add(cipt);
cipt.Show();
break;
case (int)TabControls.RolesAndSecurity:
RolesAndSecurityPseudotab raspt = new RolesAndSecurityPseudotab(currentNode);
tabPageRolesAndSecurity.Controls.Add(raspt);
raspt.Show();
break;
case (int)TabControls.InactiveInfo:
InactiveInformationPseudoTab iipt = new InactiveInformationPseudoTab(currentNode);
tabPageInactiveInfo.Controls.Add(iipt);
iipt.Show();
break;
default: {
break;
// TODO: Do something?
}
}
}
private void tabControlWorker_SelectedIndexChanged(object sender, System.EventArgs e) {
UpdateActiveTabForNode();
}
}
====
Form that serves as one of the pseudo tabPages:
public partial class BasicInfoPseudoTab : Form {
String _aNodeName = String.Empty;
public BasicInfoPseudoTab(String ANodeName) {
InitializeComponent();
// Without this, you get "TopLevel control cannot be added to a control"
this.TopLevel = false;
this.FormBorderStyle = FormBorderStyle.None;
this.Visible = true;
this.Dock = DockStyle.Fill;
_aNodeName = ANodeName;
SetDisplayVals();
}
private void SetDisplayVals() {
if (_aNodeName == "NodeBuckingham") {
textBoxFirstName.Text = "Buckingham";
textBoxLastName.Text = "Piranha";
textBoxNickname.Text = "B.P.";
}
else if (_aNodeName == "NodeVolcano") {
textBoxFirstName.Text = "Volcano";
textBoxLastName.Text = "Jerry";
textBoxNickname.Text = "V.J.";
} else if (_aNodeName == "NodeParsons") {
textBoxFirstName.Text = "Parsons";
textBoxLastName.Text = "Spalding";
textBoxNickname.Text = "P.S.";
} else {
textBoxFirstName.Text = String.Empty;
textBoxLastName.Text = String.Empty;
textBoxNickname.Text = String.Empty;
}
}
Updated:
I got it working by declaring the form variables outside the event handler and disposing them if they were not null before proceeding.
string currentNode = string.Empty;
BasicInfoPseudoTab bipt;
ConfidentialInfoPseudoTab cipt;
RolesAndSecurityPseudotab raspt;
InactiveInformationPseudoTab iipt;
. . .
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) {
currentNode = e.Node.Name;
UpdateActiveTabForNode();
}
private void UpdateActiveTabForNode() {
int ActiveTabPage = tabControlWorker.SelectedIndex;
switch (ActiveTabPage) {
case (int)TabControls.BasicInfo:
if (null != bipt) {
bipt.Dispose();
}
bipt = new BasicInfoPseudoTab(currentNode);
tabPageBasicInfo.Controls.Add(bipt);
bipt.Show();
break;
. . .
As you wish, use module level variables, one for each form, if null, new it, else as above. If you are creating forms constantly on top of each other how are you ever going to clean up? Check the size of your working set as you keep creating forms.

Get list of open windows form instance that are excuted from different assembly

I have a 'loader app' that loads a menu and when user clicks the menu image button a list view opens based on the text
(if text = employee)
(Go to class A)
(Go to class B)
...
...
(Show List View Window)
if he clicks again on the same button it opens again, I would like to prevent this.
i.e but this for a WPF application
If you want a list of the open forms, that is Application.OpenForms. You could iterate over this, using GetType() and checking the .Assembly to find those from a different assembly. Beyond that, I'm not entire clear on the question...
Assembly currentAssembly = Assembly.GetExecutingAssembly();
List<Form> formsFromOtherAssemblies = new List<Form>();
foreach (Form form in Application.OpenForms) {
if (form.GetType().Assembly != currentAssembly) {
formsFromOtherAssemblies.Add(form);
}
}
If you just want to track forms you have opened yourself, then cache that instance. Or if you use "owned forms", you can just check by name:
private void button1_Click(object sender, EventArgs e) {
foreach (Form form in OwnedForms) {
if (form.Name == "Whatever") {
form.Activate();
return;
}
}
Form child = new Form();
child.Name = "Whatever";
child.Owner = this;
child.Show(this);
}
NewProduct newproduct;
private void button1_Click(object sender, EventArgs e)
{
if(!isOpened())
{
newproduct = new NewProduct();
newproduct.Show();
}
}
private bool isOpened()
{
foreach (Form f in Application.OpenForms)
{
if (f == newproduct)
{
return true;
}
}
return false;
}
Another simple example
private Boolean FindForm(String formName)
{
foreach (Form f in Application.OpenForms)
{
if (f.Name.Equals(formName))
{
f.Location = new Point(POINT.X, POINT.Y + 22);
return true;
}
}
return false;
}
You can use a Command pattern. The loader assembly will search for commands in loaded assemblies.
For every command the loader create menu item ( or anything else, you want ), and click event will run the concrete command.
The command must know if should be created new form or used some already existing.
Mark Garvell's answer helped me to figure out what I should do, but it needed adjusting for WPF.
(In my case I wanted to close any windows not owned by the main one when it closes, but the principle is the same.)
private void EmployeeMenuItemClick(object sender, RoutedEventArgs e)
{
bool found = false;
foreach(Window w in Application.Current.Windows)
{
if(w.GetType() == typeof(EmployeeListViewWindow)
{
found = true;
break;
}
}
if(!found)
{
EmployeeListViewWindow ew = new EmployeeListViewWindow();
ew.Show();
}
}

Categories

Resources