This is a slightly different question from previous answers I have seen or I am not getting it. I have a parent class with a method named MyMethod()
and a variable public Int32 CurrentRow;
public void MyMethod()
{
this.UpdateProgressBar();
}
In the parent I create a new instance of ChildClass
Boolean loadData = true;
if (loadData)
{
ChildClass childClass = new ChildClass();
childClass.LoadData(this.Datatable);
}
In the child Class LoadData()
method I want to be able to set the CurrentRow
variable of the parent and call the MyMethod()
function.
How do I do this?
If you override a parent method in its child, child objects will always use the overridden version. But; you can use the keyword super to call the parent method, inside the body of the child method.
To call a parent component method from the child component, we need to pass the changeName() method as a prop to the child component and access it as a props data inside the child component.
You just have to create an object of the child class and call the function of the parent class using dot(.) operator.
The reference holding the child class object reference will not be able to access the members (functions or variables) of the child class. This is because the parent reference variable can only access fields that are in the parent class.
To access properties and methods of a parent class use the base
keyword. So in your child class LoadData()
method you would do this:
public class Child : Parent { public void LoadData() { base.MyMethod(); // call method of parent class base.CurrentRow = 1; // set property of parent class // other stuff... } }
Note that you would also have to change the access modifier of your parent MyMethod()
to at least protected
for the child class to access it.
Found the solution.
In the parent I declare a new instance of the ChildClass() then bind the event handler in that class to the local method in the parent
In the child class I add a public event handler:
public EventHandler UpdateProgress;
In the parent I create a new instance of this child class then bind the local parent event to the public
eventhandler
in the child
ChildClass child = new ChildClass(); child.UpdateProgress += this.MyMethod; child.LoadData(this.MyDataTable);
Then in the LoadData()
of the child class I can call
private LoadData() { this.OnMyMethod(); }
Where OnMyMethod
is:
public void OnMyMethod() { // has the event handler been assigned? if (this.UpdateProgress!= null) { // raise the event this.UpdateProgress(this, new EventArgs()); } }
This runs the event in the parent class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With