Using Methods with Object Oriented Database Development with VB.NET 2005 - Dealing with method overloading to attain more flexibility
(Page 3 of 5 )
Let us work with the method "add" now. It is defined as follows:
Public Sub add()
Dim cn As New SqlConnection("Data Source=.sql2k5;initial
catalog=sample;user id=sa;password=eXpress2005")
Dim cmd As New SqlCommand
Try
With cmd
.CommandText = "insert into sample.dbo.emp values ('" &
m_empno & "','" & m_ename & "," & m_sal & "," & m_deptno & ")"
.Connection = cn
.Connection.Open()
.ExecuteNonQuery()
End With
Catch ex As Exception
Throw New Exception(ex.Message)
Finally
If cmd.Connection.State = ConnectionState.Open Then
cmd.Connection.Close()
End If
cmd.Dispose()
cn.Dispose()
End Try
End Sub
The following is the code needed to execute the above method:
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnAdd.Click
Me.lblErrMsg.Text = ""
Try
Dim ep As New Emp
With ep
.m_empno = Me.txtEmpno.Text
.m_deptno = Me.txtDeptno.Text
.m_ename = Me.txtEname.Text
.m_sal = Me.txtSal.Text
.add()
End With
Catch ex As Exception
Me.lblErrMsg.Text = ex.Message
End Try
End Sub
From the above code, you can observe that I am assigning all the values to the fields and then only calling the method "add." But, let us consider that I would like to have one more method with the name "add" (for flexibility) which accepts all the fields as parameters. The following would be another method named "add" (apart from the old method "add").
PublicSub add(ByVal empno As String, ByVal ename As String, ByVal sal As
Double, ByVal deptno As Integer)
m_empno = empno
m_ename = ename
m_sal = sal
m_deptno = deptno
add()
End Sub
The following would be the code needed to execute the above method:
PrivateSub btnAdd_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnAdd.Click
Me.lblErrMsg.Text = ""
Try
Dim ep As New Emp
ep.add(Me.txtEmpno.Text, Me.txtEname.Text, Me.txtSal.Text,
Me.txtDeptno.Text)
Catch ex As Exception
Me.lblErrMsg.Text = ex.Message
End Try
End Sub
Now, you can observe that I defined two methods with the same name ("add"), but with a difference in parameters. You can call the two methods individually at any time. Depending on the parameters, it would automatically identify the method to execute. This is called "method overloading."
Next: Developing methods with parameters as objects >>
More Visual Basic.NET Articles
More By Jagadish Chaterjee