An Introduction to Object Oriented Database Development with VB.NET 2005 - Further expanding the class to handle additional rows
(Page 5 of 5 )
Until now, in the previous sections, we have only seen examples of fetching a single row. Now, let us expand further to handle “adding an employee” using the same class. To do this, we need to add another method in the class “emp,” named “add.” The following would be the code needed to add a new employee:
PublicSub 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
Make sure that the above method is added to the existing class “emp” and that it has no parameters as well. To access the above method, I wrote the following code for a new button:
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
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
You can observe that I am simply creating a new object, assigning values to the fields and calling the methods.
In this article, I simply wanted to explain classes, fields, methods and objects. The sample codes given in this article are neither the best in performance nor the best in programming methodologies. My upcoming articles will deal with these issues.
Any feedback, suggestions, bugs, errors, improvements etc., are highly appreciated at jag_chat@yahoo.com.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |