Creating a base Windows Forms form
I have done a base form for my window app but not sure is this correct or is there a better way to improve it.
My purpose:
- Simplify my code at UI form
- Create CRUD button to be inheri开发者_JAVA技巧ted.
Question:
How do I implement interface with the 4 button events at the UserForm.cs by right clicking the
UserForm:BaseForm
. Currently I have to manually write all 4 button event to override.My BaseForm seem to be empty. Can I put the
messageBox.show("succcess")
at mybaseForm
? Meaning to say that after run the UserForm.cs, it will run back to BaseForm. This can save up a few lines of code atuserform
.Should I put my logger at the
baseForm
too?
My baseForm.cs
public BaseForm()
{
InitializeComponent();
}
public virtual void btnSave_Click(object sender, EventArgs e)
{
}
public virtual void btnDelete_Click(object sender, EventArgs e)
{
}
public virtual void btnNew_Click(object sender, EventArgs e)
{
}
public virtual void btnReset_Click(object sender, EventArgs e)
{
}
My UserForm.cs inherit baseForm
public override void btnSave_Click(object sender, EventArgs e)
{
if (!IsValidated()) return;
BindValueToObject();
try
{
user.Add();
bindingSource.Add(user);
MessageBox.Show("Success");
}
catch(Exception ex)
{
MessageBox.Show("failed");
Logger.Error(typeof(UserForm), ex.ToString());
return;
}
}
public override void btnDelete_Click(object sender, EventArgs e)
{
base.btnDelete_Click(sender, e);
}
public override void btnNew_Click(object sender, EventArgs e)
{
base.btnNew_Click(sender, e);
}
public override void btnReset_Click(object sender, EventArgs e)
{
base.btnReset_Click(sender, e);
}
1 - At the moment the methods in your base form is declared as virtual. This means that it is optional for any derived classes to override the methods. Therefore you won't be notified asking to override them. If this is your desired behavior then you will have to manually override the methods by either writing the code yourself or getting your IDE to generate the methods for you. However, if this is not the desired behavior and you would in fact like to force all derived classes to implement these methods, then you should declare them as abstract.
2 - Any calls to those methods will trigger the overridden methods in the derived class (if it exists) and thus the code in your base class will never get executed. If you're interested in both executing the code in the derived- and the base class then you should issue a call to the base method like this
public override void btnReset_Click(object sender, EventArgs e)
{
// do form specific stuff here
someButton.Text = String.Empty;
// then invoke base method
base.btnReset_Click(sender, e);
}
3 - If you're going to do general logging for the form, then putting it in the base class would be a good idea. However, remember always to invoke the base method call in any overridden method.
精彩评论