Using Methods with Object Oriented Database Development with VB.NET 2005 - Developing methods with parameters having default values
(Page 2 of 5 )
Sometimes, it may be necessary for one or more parameters of a method to have default values. If the calling program didn't pass any values to the parameters, the default values will be taken into consideration. If the user passes values to the parameters, the default values get replaced with the values sent by the calling program.
Let us modify the same method listed in the previous section:
PublicFunction isEmployeeExist(Optional ByVal empno As String = Nothing)
As Boolean
Dim cn As New SqlConnection("Data Source=.sql2k5;initial
catalog=sample;user id=sa;password=eXpress2005")
If Not empno Is Nothing Then
m_empno = empno
End If
Dim cmd As New SqlCommand("select 'exists' from sample.dbo.emp
where empno='" & m_empno & "'", cn)
Dim found As Boolean = False
Try
cmd.Connection.Open()
Dim rd As SqlDataReader = cmd.ExecuteReader
If rd.Read() Then
found = True
End If
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
Return found
End Function
From the method above, you can understand that the parameter is mentioned as optional. Currently, I assigned the default value for the "empno" as "nothing." If the calling program doesn't pass any value to this method, it takes "m_empno" as the value to search. To execute the above method, you can work with the same code available in the previous section, or you can further modify it as follows:
PrivateSub btnSearch_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnSearch.Click
Me.lblErrMsg.Text = ""
Try
Dim ep As New Emp
ep.m_empno = Me.txtEmpno.Text
If ep.isEmployeeExist() Then
ep.load(Me.txtEmpno.Text)
Me.txtDeptno.Text = ep.m_deptno
Me.txtEname.Text = ep.m_ename
Me.txtSal.Text = ep.m_sal
Else
Throw New Exception("Employee not found")
End If
Catch ex As Exception
Me.lblErrMsg.Text = ex.Message
End Try
End Sub
Next: Dealing with method overloading to attain more flexibility >>
More Visual Basic.NET Articles
More By Jagadish Chaterjee