That's how subtyping works. When you crete an instance of the child class, all code is executing against that instance. If the base class defines handlers for events like in your case, it still executes against that instance of the child class you created. But what is it that's not working? Both events can be defined on the base class, like so:
internal abstract class MyFormBase : Form
{
DataGridView dataGridView1;
protected MyFormBase()
{
dataGridView1 = new DataGridView();
dataGridView1.CellClick += OnDataGridViewCellClick;
// Other initialization
}
protected virtual string Message
{
get { return "Message from the base class."; }
}
protected virtual void OnDataGridViewCellClick(object sender, DataGridViewCellEventArgs e)
{
// Override this in your child class if you wish.
}
protected virtual void OnDataGridViewColumnHeaderMouseClick(object sender, DataGridViewBindingCompleteEventArgs e)
{
MessageBox.Show(Message, "Test");
}
}
internal class MyChildForm : MyFormBase
{
protected override string Message
{
get { return "Message from the child class."; }
}
protected override void OnDataGridViewCellClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show("You clicked a cell.", "Test");
// Example of how to call a base method. Not always required, and in this case doesn't do anyway.
// However, for some virtual methods it's very important to call the base so read documentation.
base.OnDataGridViewCellClick(sender, e);
}
}
Now when you create an instance of MyChildForm and click a column header, you'll see "Message from the child class" even though the event handler is defined in the base class. It calls the virtual (overridable) property which IS the property on the MyChildForm instance. If you want to call the base class's method, use base
. You also overrided the CellClick event handler which will show "You clicked a cell." I also show an example of calling the base class's method though in this case it doesn't do anyway. If it would never do anything, define it as abstract
instead of virtual
and remove the body like so:
private abstract void OnDataGridViewCellClick(object sender, DataGridViewCellEventArgs e);
Hopefully this shows you an example of how polymorphism is working such that you can define your handlers in your base class but have it access the data - expectedly - in the child class.