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
tryblock 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 thetryblock succeeds.