c# : how to identify from which childform was a button (belonging to a parentForm) clicked on?
I have 4 ChildForm(1..4)开发者_如何学Go whose base class is the ParentForm.
ParentForm has a button .
Is there a way to know from which ChildForm was the button actually clicked?
Controls have a Parent or Page property, can you use one of those?
Yes, with a bit of reflection you can do it. In the eventhandler user the sender
object to get the type of the parent:
Type ChildFormType = ((Button)sender).Parent.GetType();
However, having to use reflection (query the type system) is often a sign of bad design. Some kind of Visitor Pattern implementation where the ParentForm
as an abstract accept
method might be a solution.
I understand that you have got 4 different classes for your 4 forms, all derived from the ParentForm. If this is the case, I would implement the ButtonClicked method in this way:
private void button1_Click(object sender, EventArgs e)
{
// part common to all the forms (possibly void)
specific_button1_Click(sender, e);
// part common to all the forms (possibly void)
}
protected void specific_button1_Click(object sender, EventArgs e)
{
}
and then override the specific_button1_Click method in the derived forms
精彩评论