This tip was submitted to the VS.NET Info Center by member Edwin Steenstra. Please let other users know how useful
it is by rating it below. Do you have a tip or code of your own you'd like to share? Submit it here.
By using inheritance, source code can be made simpler and more robust. In this case, I'm dealing with stored procedures to write the contents of various forms to SQL Server. By using inherited forms from a form called BaseTable, in which all actions are predefined, I only have to worry about the parameters of the command object.
Public Class BaseTable Inherits System.Windows.Forms.Form ' 'Just the piece of code for saving an item is given ' Protected Overridable Sub AddPutParameters(ByVal Cmd As SqlClient.SqlCommand) End Sub Public Sub SaveItem() Dim Success As Boolean = True Try Dim Cmd As New SqlClient.SqlCommand() Cmd.Connection = New SqlClient.SqlConnection(_connectionString) Cmd.Connection.Open() Cmd.CommandType = CommandType.StoredProcedure Cmd.Parameters.Add(New SqlClient.SqlParameter("@id", SqlDbType.UniqueIdentifier)) Cmd.Parameters("@id").Direction = ParameterDirection.Output AddPutParameters(Cmd) Cmd.ExecuteNonQuery() Catch ex As Exception Success = False End Try If Success Then HandleSuccess End If End Sub End Class
To save a record in the derived forms you just have to implement the parameters that are specific to the table the form handles.
Public Class frm_COUNTRY Inherits BaseTable Protected Overrides Sub AddPutParameters(ByVal Cmd As SqlClient.SqlCommand) Cmd.Parameters.Add("@name", _name.Text) Cmd.Parameters.Add("@code", _code.Text) Cmd.CommandText="_spPUT_COUNTRY" End Sub