Problem solve Get help with specific problems with your technologies, process and projects.

Use inheritance on forms for simpler and more robust source code

By using inheritance, source code can be made simpler and more robust.

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

            Dim Cmd As New SqlClient.SqlCommand()
            Cmd.Connection = New SqlClient.SqlConnection(_connectionString)
            Cmd.CommandType = CommandType.StoredProcedure
            Cmd.Parameters.Add(New SqlClient.SqlParameter("@id", SqlDbType.UniqueIdentifier))
            Cmd.Parameters("@id").Direction = ParameterDirection.Output
        Catch ex As Exception
            Success = False
        End Try

        If Success Then
        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)

    End Sub

Dig Deeper on .NET tutorials, guides and quizzes

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.