Accessing Main Form From Child Form - c#

I have a simple problem: I have a main form in win-forms/c#. It has a listbox bound to a database.
When I click a button a new form is created.
When I click a button on the child form, I want to call a method that exists in the main form, that updates the list box or alternatively when the child form closes, to call that function.
Is this possible??

There are many ways to achieve this, but here's a simple way. In your main form, when you create and show a child form, do it like this:
ChildForm child = new ChildForm();
child.Show(this); // this calls the override that takes Owner parameter
Then, when you need to call a method in the main form from the child form, use code like this (assumes your main form is of type MainForm):
MainForm parent = (MainForm)this.Owner;
parent.CallCustomMethod();
A more complex way would be to use a form of dependency injection, where you would pass in a reference to the parent form (or more properly, to its interface) in the constructor of the child form. But the above way is simple and probably effective enough for your purposes (and it actually is a form of dependency injection itself, sort of).

Scenario 1: Call a method in Parent Form on click of button in child form.
Create an Event in Child Form. Raise that event on some Button Click etc. Subscribe to that event in your Parent Form and call the parent's form method inside that.
Scenario 2: Call a method in Parent Form when Child Form is closed.
Handle the FormClosed or FormClosing event of Child Form in the Parent form and call the parent's form method inside that.
ChildForm frm = new ChildForm();
frm.FormClosed += new FormClosedEventHandler(frm_FormClosed);
void frm_FormClosed(object sender, FormClosedEventArgs e)
{
//Call your method here.
}

Related

How to show new form without disabling the parent form?

I have shown a new form in button click on parent form like below,
Here the background parent form gets disabled when a new child form is activated.
Is there any available options to show the child form without disabling the parent form?
Regards,
The Show function shows the form in a non modal form. This means that you can click on the parent form.
ShowDialog shows the form modally, meaning you cannot go to the parent form
Application.Run() runs the main parent form, and makes that form the main form. Application.Run() is usually found in main.
If it is fully disabled (no interaction possible), you are using .ShowDialog() on the child form instead of .Show(). If you use .Show() you will be able to use both forms
Example:
ChildForm childForm = new ChildForm();
childForm.Show();
after you open the new form and call this.Activate(); it will refocus on the parent window, but this will cause it to loose focus for a fraction of a second

Disabling Button In Parent Form Child Form

I have two forms. One is a parent form with a button and a child form with a radio button. i want to enable/disable Button in parent Form Based on if the Radio Button in Child Form is Enabled. Should i raise an event or there is an alternative way to achieve this.??
Events are a nice and robust way to handle this.
They will take a bit more code, but it could be worth it if you want a robust solution that you can extend in the future, etc.
On the other hand, if you just want to quickly solve your problem, there are two more commmon solutions.
when you create the child form, you can pass it a reference to the parrent form that created it (through the constructor)
something like
public partial class Form2 : Form
{
private Form1 parrentForm;
public Form2(Form1 parrent)
{
parrentForm = parrent;
}
When you create the child form, you pass it the reference
//from inside Form1
Form2 frm2 = new Form2(this);
You might declare a public method inside Form1
public void EnableButton() {
}
then call it from form2 with the reference you stored
parrentForm.EnableButton();
you can even make the button in Form1 public (from the gui, select the button, in the properties pane change the "Accessibility" property to "Public" instead of "Private" which is default.
Then in form2 you could do
parrentForm.Button1.Enabled = false;
these are all quick and somewhat dirty solutions.
Events are more clear for complex uses.
In the end, go with what makes the most sense.
I like the answer above but just to mention, you could use an event as well.
public event EventArg RadioButtonHasChanged;

How to refresh a current form in C#?

I am creating a multiple form windows application using C#, I have two form one Parent form and a child form.
From parent form I called the child form to add a tree node in the parent form treeview. After entering the details in the child form and pressing "Add" button I want to close the child form and want to add the tree node in the treeview dynamically inside the parent form.
The value is passing perfect, I am using properties for the transfer. Rest by using this.Show() another parent form opens up. I have already tried Invalidate() and Refresh() but the treeview does not get updated.
Override child form constructor to accept parent form as parameter
ChiildForm chilForm=new ChildForm(parentFormObject);
Now you can call method of parent form that would make the required change on the page.
parentFormObject.RefreshSection();
but the treeview does not get updated
To refresh the treeview you need to rebind it to your datasource after adding the newly added item of child form.
Example:
List<SomeClass> items = new List<SomeClass>();
if(childForm.ShowDialog() == DialogResult.Ok)
{
items.Add(childForm.newlyAddedItem); //you have mentioned that values are passing perfect
//your code for rebinding to the treeview
}
If you want to refresh after clicking Add buttons,
just try to call the load_ function by sending the parameters.
example,
button_click(Object sender,Event_args e)
{
Form_Load(sender,e);
}

Access an existing main winform instance from any child form

I am working a WinForm Application. I have a couple of forms on it. I want to be able to access my main form from any child form. I was able to do that through a custom button function and capture the Form_Closing event. I have one problem though which I'll explain below.
The code on the main form is as follow:
ChildForm form = new ChildForm(); // Create new Child Form instance
form.Show(); // Show Child form
this.Hide(); // Hide Main form
Using "this.Hide();" means that the main form still exists in memory and is still working, it's just hidden which is what I want.
The code on the child form
MainForm form = new MainForm(); // Create new Main Form instance
form.Show(); // Show Main Form
this.Close(); // Close Child Form
This is all well except on my second code block (Child Form directly above), the first line of code, creates a new instance of the main form. That is my problem, I don't want to create a new instance of that form, I want to show the already existing hidden instance (The main form I hid in the first block of code above).
I tried the following code on the Child form:
this.Parent.Show();
But I got this runtime error message:
"System.NullReferenceException was unhandled: Message=Object reference not set to an instance of an object".
I understand what the error means, I just don't the code to create an object reference to that main form or how to reference it in any sort.
Any tips please?
Thanks ahead.
You can make a constructor for your other forms that takes in a window as a parameter
private Form MyParent { get; set; }
public Form1(Form parent)
{
MyParent = parent;
}
MyParent.Show();
where MyParent is a property of the form
you can call this via new ChildForm(this)
Edit
I just looked, not sure why I can't use a constructor for an IWin32Window but Show has an overload that takes one in which will set the Owner to a parent form
new ChildForm().Show(this);
ChildForm.Owner //returns MainForm (parent)
That should do it. Because these are single thread forms, the function will wait till you close the form before proceeding further.
ChildForm form = new ChildForm(); // Create new Child Form instance
this.Hide(); // Hide Main form
form.ShowDialog(); // Show Child form, wait for closing
this.Show();
You can also attach ChildForm closing event to function in MainForm.
public MainForm()
{
ChildForm form = new ChildForm();
form.FormClosed += OnClosed;
}
public void OnClosed(object sender, EventArgs e)
{
this.Show();
}

C# Parent form not updating from child

I have two Forms
Parent Form : properties : Total Value. Button to load child form.
Child Form: property : insert Value.
When I run application, Parent form loaded first. I can load second (Child) form by click button.
Problem is that when I insert value in child form parent form is not showing any changes even I pass value by delegate and other methods.
I don't want to reload Parent Window. Please help
What you should be doing is creating events on the child for (or using the existing events if they will do the job) and having the parent form subscribe to those events.
One common example is to have the parent hide itself, show the child, and then show itself again when the child is closed. Here is some code that does that:
//in parent form
private void someButtonClickHander(object sender, EventArgs args)
{
ChildForm child = new ChildForm();
this.Hide();
child.Closing += (sender2, args2) =>
{
var someResultFromChildForm = child.SomePropertyOnChildForm;
this.Show();
}
child.Show();
}
If the closing event doesn't work for you (maybe you want to do something when the child form presses a button) you may need to have the child create it's own event. There are lots of tutorials on MSDN or other sites on how to do this. If you have trouble with that (or any other aspect of this design) please ask for clarifications in comments.
If you want to keep data consistent between multiple forms, I recommend putting the data into an object that you can reach from both forms.
The most direct way is to implement INotifyPropertyChanged for the object, so you can bind to this object in both forms and any changes made will trigger the property change event.
For more complex scenarios I make an object that has custom events that I can subscribe to, as INotifyPropertyChanged can be lack the subtlety needed in complex scenarios. As an example, I have a "Helm" object for my primary navigation form that all of the UI elements subscribe to. If a navigation event occurs, the helm does all of the navigation and data loading, and then it triggers a series of events that the UI listens to.
For a simple parent child this can seem like overkill, but this model (having one truth for the current state that the UI simply subscribes to) allows your UI to evolve and for each element of the UI to only worry about its own needs.
Have a Property called Parent in your child form. When you create the instance of the Child,Pass the current object( parent form object) to the constructor where you will set it as the Parent property value of child. In Parent form Have a Public Method in your Parent form. P
parent form
Form1 : Form
{
decimal _totalPrice;
public void UpdateTotal(decimal val)
{
_totalPrice=_totalPrice+val;
lblTotal.Text=_totalPrice.ToString();
}
}
Child Form
Form2:Form
{
public Form1 Parent { set;get;}
public Form2(Parent parent)
{
this.Parent =parent;
}
}
When creating the object of Child form
Form2 objChjild=new Child(this);
//do whatever
Now from child form, if you want to update the total,
call like this
this.Parent.UpdateTotal(200);

Categories