Using Constructors with Object Oriented Database Development with VB.NET 2005 - Defining constructors with parameters in a class
(Page 2 of 5 )
Just like methods in a class, a constructor can also have parameters. This provides a great advantage sometimes when initializing objects with some values. Let us modify the constructor defined in the previous section as follows:
Public Class Emp
Private m_empno As String
Private m_ename As String
Private m_sal As Double
Private m_deptno As Integer
Private m_errMsg As String
Public Sub New(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
m_errMsg = ""
End Sub
...
End Class
The above class is defined with a constructor with parameters. In the above case, we cannot simply create an object with the "new" keyword. The declaration of the object should look something like the following:
Dim ep As New Emp("1001", "jag", 1000, 10)
The above statement creates and instantiates an object by calling the constructor with parameters. We can rewrite our code for "btnAdd_Click" as follows:
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(Me.txtEmpno.Text, Me.txtEname.Text,
Me.txtSal.Text, Me.txtDeptno.Text)
ep.add()
Catch ex As Exception
Me.lblErrMsg.Text = ex.Message
End Try
End Sub
Next: Constructor overloading within a class >>
More Visual Basic.NET Articles
More By Jagadish Chaterjee