How to Design a Second Form? - c#

i'm trying to make a second form and acces to all of the main form methods, values, etc... so what i do is:
public partial class Principal : Form
{
public Principal()
{
InitializeComponent();
}
...
And in one method i have...
private void agregarUsuarioToolStripMenuItem_Click(object sender, EventArgs e)
{
Form Form2 = new Form();
Form2.Show();
}
I suppose that in Form2 i could acces to all of what i have in my main form, but i wonder how to edit this Form2, how to put buttons or stuff, cause i didnt create a form, just another instance of Form().

First of all, you cannot access the values on the main form from the second form unless the second form has a reference to the first main form. They are completely separate instances. The second form is only another copy of the template (the type) that the first form was created from. All state or data in the first form is specific to the instance of the form (unless declared as static). All the controls and visual elements defined in the forms template are created in each of the instances from the template when the form is instantiated (when the constructor runs).
If you need the second form to refer to values on the first form, how to do this best depends on how, when and why.... If you only need to do this when the second form is constructed, and never again during the lifetime of the first form, then you can do it during construction ( Form Form2 = new Form(); ) if you have a reference to the first instance of the form. If you need access to the values on the first instance later as well (during the lifetime of the second instance), then you need to add a reference to the first instance as a private field or property of the form so that code on instances of the second form will always have a reference to the first instance. The best way os to make the second instance an instance of a derived (child) of the first form that has this additional property, and pass the reference to the first form in the constructor to of this second derived form type
public SecondForm: Principal
{
public Form PrincipalForm { get; set; }
public SecondForm(Principal principalForm)
{
InitializeComponent();
PrincipalForm = principalForm;
}
// other stuff
}
then, when you create the second instance, create an instance of SecondForm instead. It will look exactly like the first instance, (cause it derives everything defined on Principal), but will have this one additional property.
private void agregarUsuarioToolStripMenuItem_Click(object sender, EventArgs e)
{
SecondForm Form2 = new SecondForm(firstPrincipalForm);
Form2.Show();
}
now, everywhere on the second forms internal and public methods and code you will have a reference to the first form to do with as you wish

Related

How to edit a checkedListBox within main form from another class?

It's probably a silly question, but I really don't know how to handle it.
My main form default class looks like this:
public partial class MainForm : Form
{
public MainForm(bool version)
{
InitializeComponent();
if(version == true)
{
items_checkedListBox.Items.Add("aa".ToString());
}
else
{
Controls.Remove(items_checkedListBox);
}
}
}
By default, my WinForm app starts with Application.Run(new MainForm(true)); and everything is ok. But I want to update the checkedListBox from another class and for that I need to instantiate my main form object and I call the new object with MainForm mainForm = new MainForm(false); but the problem is that the checkedList control remains, even though Controls.Remove(items_checkedListBox); gets executed.
How could I manipulate a control from another class when I instantiate the main form? :(
By doing this:
MainForm mainForm = new MainForm(false);
you create a new second form of the type MainForm and delete it's control items_checkedListBox, but that's not the control which you see on your first form of MainForm. Furthermore you don't see the second form you created, because you didn't make it show up, so don't wonder that you don't see anything happening like the removal of the other control on the second form.
So in order to manipulate your control items_checkedListBox you need to pass the reference of this control to your class in which you wish to manipulate it.
Imagine you would have another form (which is your other class), which you use to manipulate your control items_checkedListBox.
public partial class FmManipulateControl : Form
{
public FmManipulateControl()
{
InitializeComponent();
}
}
In order to be able to do this, pass a reference of this control as method parameter to the constructor:
public FmManipulateControl(Control myControl) { ... }
So that we can manipulate it we store this reference of our control in a field, so e.g. a button click event can access the control to change/remove/... it.
Control controlToChange;
public FmManipulateControl(Control myControl)
{
InitializeComponent();
controlToChange = myControl;
}
Let's imagine we bind to a button click event in our form FmManipulateControl:
private void button1_Click(object sender, EventArgs e)
{
//diposes the control, so it does not exist anymore, but you can apply
//any change to the control you wish to do
controlToChange.Dispose();
}
Now all you have to do is to create an instance of FmManipulateControl and pass it a reference of the control items_checkedListBox and show the new form object.
FmManipulateControl fmChangeAControl = new FmManipulateControl( items_checkedListBox);
fmChangeAControl.Show();
Further explaination about the reference type:
I am talking about passing a reference of the control and I think you might wonder about what I mean by that. I suggest you to read about value and reference types.
I try to keep it short and simple.
Imagine a value type contains the value directly itself: e.g. an int. The object contains the value directly.
int a = 3;
a contains the value 3.
Now let's have a look at our control. This ListBox control items_checkedListBox does not contain our object control, but a reference to it's location in memory. That's why it is called reference type.
So when we pass items_checkedListBox as a method parameter, we don't pass an object, but the memory location of our items_checkedListBox control. So we point to the same object, so we are abel to manipulate it.
Note:
Method parameters are just a copy of the inputted object, so when we do:
FmManipulateControl fmChangeAControl = new FmManipulateControl( items_checkedListBox);
In our form fmChangeAControl we got an object(myControl) which is a copy of items_checkedListBox. But since we did not pass the object, but a reference it does not matter if we have a copy or not, we still point to the same memory location so we still manipulate the same object.

accessing a function from different form

In my program I have two forms. The main form and a form where you fill in extra information. What I'm trying to do is to write out the information given on the second form on a list box when the 'ok' button is pressed.
Currently this is what I have:
Main form:
public void writeLine()
{
foreach (var item in VarClass.listItems[VarClass.count - 1])
{
listBox1.Items.Add(item.ToString());
}
}
Second form:
Form1.writeLine();
As it, I get the following error at 'Form1.writeLine();'
"An object reference is required for the non-static field, method or property..."
I can kinda fix this by making 'writeLine()' static in the main form, but then I get the same error on 'listBox1' in the main form. How do I fix this?
You should pass the reference of your main form to the second form and call the method on that reference. For example you can create a property on the second form like private Form _mainForm; and create a constructor of the second form to receive that reference and set to that field. After that you will be able to call _mainForm.writeLine() in your second form.
Create an instance of Form1 and call the method. Here is the code:
new Form1().writeLine();
There are a couple ways to handle this. One is for form2 to have a reference back to the calling form ideally through an interface rather than a reference to the concrete class.
Another option would be for Form2 to have an event that form1 could subscribe to that would inform form1 that form2 has some output.
Keep a reference to the second form from the first:
public MyFirstForm
{
...
public MyFunction()
{
MySecondForm secondForm = new MySecondForm();
// ... Open your form etc, look for when it's complete and then ...
// Read the values from the second form into the first
var MyValues = secondForm.getValues();
// Now populate the list-box with the information returned.
//for (my listbox)
}
}

Refreshing object on separate form

I have an application that shows data from a MySQL table. Basically, my application consists of two forms: the main form, and a form for adding stuff to the database.
The main form shows all the entries in the database and relevant information. When the user wants to add a new entry to the database, a secondary form is opened that prompts for information. Once the information is filled out, the user presses a Submit button and the form closes. My problem is that when the secondary form closes, the listBox in the main form doesn’t update to reflect the newly-added entry.
Here is the code that is executed when the user submits the secondary form:
private void closeWindow()
{
mainForm parent = new mainForm();
parent.listParts.Refresh();
this.Close();
}
Is there a reason when I call the listBox to be refreshed, it doesn’t show my newly-added information? Perhaps I am calling something in the wrong order? Or does the Refresh() method not even work like that?
Any help would be appreciated! Alternatively, if you know of a better way to do this, I’d love to hear it!
The problem is that you're refreshing the wrong form:
private void closeWindow()
{
mainForm parent = new mainForm();
parent.listParts.Refresh();
this.Close();
}
Since you use: new mainForm(), you're allocating a completely separate instance of the "mainForm", and refreshing it's content. This will not effect the existing, opened form.
I would recommend passing a reference to the mainForm to the constructor of the secondary form. It then would know which instance of mainForm it needs to use to call Refresh().
Reed has given an answer with why what you did din't work, here's one possible solution for how to actually fix it:
in some event handler for MainForm:
var otherForm = new SomeOtherForm();
otherForm.Closed += (sender, args) =>
{
//update the listbox in MainForm here
};
If you need information from the second form to update the listbox, then make a public property in SomeOtherForm that exposes the data needed by MainForm.
I think you should reload the data again. fetch it again set the datasource
Have a Parent Property to your child form which is of type of your First form.
some thing like this.
Your Parent form
public partial class KitTypes : Form
{
public void ReloadData()
{
// Get the data and Set as datasource of control
}
}
And the Child form
public partial class Kit : Form
{
private int _KitId=0;
private KitTypes _parentForm = null;
public Kit(KitTypes parentForm)
{
_parentForm =parentForm;
}
}
And from your First form, when you create an object of this, pass the parent form as the parameter
Kit objChild=new kit(this);
objChild.Show();
Now in your child, form you can call the public method of parent form like this
this._parentForm.ReloadData();

Accessing the parent Form

I know that the title might seem silly, couldn't think of something better, sorry.
I have 2 Forms (C#), the main-form holds an instance of the second.
Is there a way to.. get access to the running instance of Form1 (The entry point) and to his properties from the instance of form2?
Everybody tells me to learn OOP.
I did, a long long time ago, and I still don"t get it.
When the main form instantiates the second form, it could pass a reference to itself to the constructor of the second form.
Thus, the second form will have access to the public members of the first.
EDIT
In the Form1 you instantiate Form2 somewhere and pass it a reference to Form1 in ctor:
Form2 f2 = new Form2(this);
In the class definition of Form2 add a field:
private Form1 m_form = null;
In the constructor of the second form set that field:
public Form2(Form1 f)
{
m_form = f;
}
Then, everywhere in your Form2 you have access to Form1 through the means of m_form
You probably instanciated Form2 from within Form1. After instanciating and BEFORE showing it you could set a property on Form2 that refers to Form1 like this:
Form2 f2 = new Form2();
f2.TheParent = this;
f2.Show();
Of course you have to add the TheParent property to the Form2 class to be able to do that.
Warning: although it is possible this way a better solution might be to create a seperate object that holds all required/shared data andd pass that object to each form in a similar way. This will prevent your code from becoming too coupled.
One approach to this can be creating an owner-owned relationship.
// Create a form and make this form its owner
Form ownedForm = new Form();
ownedForm.Owner = this;
ownedForm.Show();
or as a shortcut, you could pass the owner form as an argument to an overload of the Show method, which also takes an IWin32Window parameter
ownedForm.Show(this); // established owner-owned relationship
Then you could access the main form properties like this
((MainForm)this.Owner).ownerVariable;
In order for this variable/method to be accessible, it has to have the internal protection modifier.

How can I update a label on one form from another form in C#?

I want to update label of Form1 from Form2. So here's what I have:
// Form1
public string Label1
{
get { return this.label1.Text; }
set { this.label1.Text = value; }
}
// Form2
private void button1_Click(object sender, EventArgs e)
{
Form1 frm1 = new Form1();
frm1.Label1 = this.textBox1.Text;
this.Close();
}
So the above code doesn't work. However, when I add the following:
frm1.Show();
after
this.Close();
in Form2 code, the Form1 obviously is being opened again (two windows). But I want it to update in the same window so I suggest this.Close() is unnecessary.
Anyone have any ideas?
In the button1_Click method, you're actually creating a new instance of Form1 and setting the Label1 property of that new instance. That explains why a second instance of Form1 is being shown on the screen when you add frm1.Show();. If you look at that second copy carefully, you'll see that it's label displays the correct value, but your original copy of that form retains its original value.
Instead, I assume that what you want to do is set the Label1 property for the existing instance of Form1 that is already displayed on the screen. In order to do that, you're going to have to get a reference to that existing form object.
Thus, this becomes a simple question of "how do I pass data between two objects (forms)", which has been asked countless times here on Stack Overflow. See the answers to these related questions:
Communicate between two windows forms in C#
Passing values between two windows forms
C# beginner help, How do I pass a value from a child back to the parent form?
Send values from one form to another form in c# winforms application
Try using singleton design pattern for that as I think the problem is when you using new
public class Form1Singleton {
private static final Form1Singleton INSTANCE = null;
// Private constructor prevents instantiation from other classes
private Form1Singleton () {
}
public static Form1Singleton getInstance()
{
if(INSTANCE ==null)
INSTANCE =new Form1Singleton();
return INSTANCE;
}
}
Now you can use the form easily only 1 form
private void button1_Click(object sender, EventArgs e)
{
Form1Singleton frm1 = Form1Singleton.getInstance();
frm1.Label1 = this.textBox1.Text;
this.Close();
}
I hope that solve your problem
BR,
Mohammed Thabet Zaky
Most probably: What you actually do is create a brand new instance of Form1 within the scope of Form2, while later in the control flow of your program another instance of Form1 is created and shown. Of course, in such a case you can't expect your label to be set correctly.
The best would be to decouple Form1 and Form2 from each other and instead pass only data along the control flow of your program.
When you say this.close that means all the values you set to that instance gets nullifies.
You can use delegate here, to set form values.
MVP pattern is good for this type of senario and also separate UI and business logic.
This thread is good reference:
UI Design Pattern for Windows Forms (like MVVM for WPF)

Categories