In my app I have a lot of copy and paste code that is exactly the same and performs exactly the same function (button click events and the like). These redundant code live in the code-behind of many of my pages. So I decided to reduce the code duplication and to move these methods into a class file and only make a call to them from the code-behind pages.
Here is an example of a button click event in my code behind calling the methods from a class file:
#region DELETE selected users - button
protected void btnDeleteSelected_Click(object sender, EventArgs e)
{
try
{
UserGvUtil.DeleteSelectedUsersAndProfiles(GridView1, Msg);
}
catch (Exception ex)
{
UserGvUtil.ExceptionErrorMessage(Msg, ex);
}
finally
{
UserGvUtil.RefreshGridView(GridView1);
}
}
#endregion
Can I combine this try/catch block into yet another method and move it to the same class file? So, the only thing I have in the click event is a single line of code.
Does it make sense to do this? Not sure why, but I would like to have my code behind files as clean and simple as possible so I can make all the edits in a single place.
Sorry if I make no sense. I'm just learning about classes and methods and it floods my head with lots of ideas.
You can move the stuff inside the try block into an anonymous delegate that you pass to a shared method that has a try/catch. You really don't need to put the refresh into the finally, though. In fact, I would think you would only want to run it if the try block succeeds.
You can wire the event handlers manually.
btnDeleteSelected1.Click += Events.BtnDeleteSelected_Click;
btnDeleteSelected2.Click += Events.BtnDeleteSelected_Click;
...
btnDeleteSelected3.Click += Events.BtnDeleteSelected_Click;
public static class Events
{
public static BtnDeleteSelected_Click(object sender, EventArgs e)
{
...
}
}
Edit (for downvoters: ???) The code will give you a one liner and you won't have to worry about writing custom events when they are all the same.
Also, if the utility methods have the same signature you could have a generic method:
public void ExecuteGvMethod(Action<GridView, string> gvMethod, GridView gv, string msg)
{
try
{
gvMethod(gv, msg);
}
catch (Exception ex)
{
UserGvUtil.ExceptionErrorMessage(msg, ex);
}
finally
{
UserGvUtil.RefreshGridView(GridView1);
}
}
And in code:
public static class Events
{
public static BtnDeleteSelected_Click(object sender, EventArgs e)
{
ExecuteGvMethod(UserGvUtil.DeleteSelectedUsersAndProfiles, (GridView)sender, "hi of whatever");
}
}
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