Está en la página 1de 9

Tres Capas en VB.

NET
Primero deberemos trabajar sobre una solución en blanco e ir
añadiendo bibliotecas de clases, tal como se muestra en el Solution
Explorer:

La base de datos que usaremos en el ejemplo se llama prueba y


trabajaremos sobre la tabla empleado que tiene los siguientes
campos:
Listo, ahora nos vamos a trabajar con la capa entidad(CEntidad)
especificamente sobre la clase: Clase_Empleado y lo primero que
debemos fijarnos es que sea Public:

Public Class Clase_Empleado

End Class

en VB parece que no es un problema porque al agregar una clase la


crea como Public pero en C# si se deberá especificar, por el momento
sigamos y nos vamos a basar en la tabla empleados, lo que haremos
sera crear un atributo y propiedad respectiva para cada campo en la
tabla empleado, esto para hacer referencia a la tabla mientras
realizamos operaciones sobre la base de datos, entonces
el código para Clase_Empleado es:

Public Class Clase_Empleado

Private codigo_ As String


Private nombres_ As String
Private departamento_ As String
Private cargo_ As String
Private jefe_ As String

Public Property codigo() As String


Get
Return codigo_
End Get
Set(ByVal value As String)
codigo_ = value
End Set
End Property

Public Property nombres() As String


Get
Return nombres_
End Get
Set(ByVal value As String)
nombres_ = value
End Set
End Property

Public Property cargo() As String


Get
Return cargo_
End Get
Set(ByVal value As String)
cargo_ = value
End Set
End Property

Public Property jefe() As String


Get
Return jefe_
End Get
Set(ByVal value As String)
jefe_ = value
End Set
End Property

Public Property departamento() As String


Get
Return departamento_
End Get
Set(ByVal value As String)
departamento_ = value
End Set
End Property

End Class

Bueno, ahora nos vamos a la capa de datos=CDatos y hacemos la conexión a la base de datos y
sera aquí donde se realizaran todas las acciones sobre empleado(Actualizar, Eliminar, Modificar y Consultar),
nos queda así:

Imports CEntidad
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Public Class Clase_Datos


Dim conexion As String = ConfigurationManager.ConnectionStrings("cnn").ConnectionS
tring

Public Function MostrarDatos() As List(Of Clase_Empleado)


Dim lista As New List(Of Clase_Empleado)
Dim dr As SqlDataReader = Nothing
Using Sql As New SqlConnection(conexion)
Sql.Open()
Using cmd As New SqlCommand("SeleccionarDatos", Sql)
cmd.Connection = Sql
cmd.CommandType = CommandType.StoredProcedure
dr = cmd.ExecuteReader
While dr.Read
Dim list As New Clase_Empleado
list.codigo = dr.Item("codigo")
list.nombres = dr.Item("nombres")
list.cargo = dr.Item("cargo")
list.jefe = dr.Item("jefe")
list.departamento = dr.Item("departamento")
lista.Add(list)
End While
End Using
End Using
Return lista
End Function

Public Function IngresarDatos(datos As Clase_Empleado) As Boolean

If datos Is Nothing Then


Throw New ArgumentException("no se recibieron datos en InsertarDatos")
End If

Dim trans As SqlTransaction = Nothing


Dim codigo As String = datos.codigo
Dim nombres As String = datos.nombres
Dim cargo As String = datos.cargo
Dim jefe As String = datos.jefe
Dim departamento As String = datos.departamento

Try

Using Sql As New SqlConnection(conexion)


Sql.Open()
trans = Sql.BeginTransaction(IsolationLevel.ReadCommitted)
Using cmd As New SqlCommand("InsertarDatos", Sql, trans)
cmd.Transaction=trans
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@codigo", codigo)
cmd.Parameters.AddWithValue("@nombres", nombres)
cmd.Parameters.AddWithValue("@cargo", cargo)
cmd.Parameters.AddWithValue("@jefe", jefe)
cmd.Parameters.AddWithValue("@departamento", departamento)
If (cmd.ExecuteNonQuery = 1) Then
trans.Commit()
Return True
Else
Return False
End If
End Using
End Using
Catch ex As Exception
trans.Rollback()
Return False
Throw New ArgumentException("Verificar InsertarDatos")
End Try
End Function

Public Function ModificarDatos(datos As Clase_Empleado) As Boolean

If datos Is Nothing Then


Throw New ArgumentException("no se recibieron datos en ModificarDatos")
End If

Dim trans As SqlTransaction = Nothing


Dim codigo As String = datos.codigo
Dim nombres As String = datos.nombres
Dim cargo As String = datos.cargo
Dim jefe As String = datos.jefe
Dim departamento As String = datos.departamento

Try

Using Sql As New SqlConnection(conexion)


Sql.Open()
trans = Sql.BeginTransaction(IsolationLevel.ReadCommitted)
Using cmd As New SqlCommand("ModificarDatos", Sql, trans)
cmd.Transaction = trans
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@codigo", codigo)
cmd.Parameters.AddWithValue("@nombres", nombres)
cmd.Parameters.AddWithValue("@cargo", cargo)
cmd.Parameters.AddWithValue("@jefe", jefe)
cmd.Parameters.AddWithValue("@departamento", departamento)
If (cmd.ExecuteNonQuery = 1) Then
trans.Commit()
Return True
Else
Return False
End If
End Using
End Using
Catch ex As Exception
trans.Rollback()
Return False
Throw New ArgumentException("Verificar ModificarDatos")
End Try
End Function

Public Function EliminarDatos(param As String) As Boolean


Dim trans As SqlTransaction = Nothing
Try
Using Sql As New SqlConnection(conexion)
Sql.Open()
trans = Sql.BeginTransaction(IsolationLevel.ReadCommitted)
Using cmd As New SqlCommand("BorrarDatos", Sql, trans)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@codigo", param)
If (cmd.ExecuteNonQuery = 1) Then
trans.Commit()
Return True
Else
Return False
End If
End Using
End Using
Catch ex As Exception
trans.Rollback()
Throw New ArgumentException("Error en BorrarDatos")
End Try
End Function

End Class

Vamos ahora con la clase negocio

Imports CDatos
Imports CEntidad

Public Class Clase_Negocio


Dim objdatos As New CDatos.Clase_Datos
Public Function Mostrar() As List(Of Clase_Empleado)

Return objdatos.MostrarDatos
End Function

Public Function IngresarDatos(datos As Clase_Empleado) As Boolean


Return objdatos.IngresarDatos(datos)
End Function

Public Function ModificarDatos(datos As Clase_Empleado) As Boolean


Return objdatos.ModificarDatos(datos)
End Function

Public Function EliminarDatos(codigo As String) As Boolean


Return objdatos.EliminarDatos(codigo)
End Function

End Class

y por ultimo el formulario que queda así y su respectivo código


Imports CEntidad
Imports CNegocio

Public Class Show


Dim objnegocio As New CNegocio.Clase_Negocio

Private Sub Show_Load(sender As System.Object,


e As System.EventArgs) HandlesMyBase.Load
cargar()
End Sub

Private Sub cargar()


Dim bs As New BindingSource
bs.DataSource = objnegocio.Mostrar
DataGridView1.DataSource = bs
BindingNavigator1.BindingSource = bs
TCodigo.DataBindings.Clear()
TCodigo.DataBindings.Add(New Binding("text", bs, "codigo"))
TNombres.DataBindings.Clear()
TNombres.DataBindings.Add(New Binding("text", bs, "nombres"))
TCargo.DataBindings.Clear()
TCargo.DataBindings.Add(New Binding("text", bs, "cargo"))
TJefe.DataBindings.Clear()
TJefe.DataBindings.Add(New Binding("text", bs, "jefe"))
TDepartamento.DataBindings.Clear()
TDepartamento.DataBindings.Add(New Binding("text", bs, "departamento"))
End Sub

Private Sub BAgregar_Click(sender As System.Object,


e As System.EventArgs) HandlesBAgregar.Click
Dim lista As New Clase_Empleado
If (Not (String.IsNullOrEmpty(TCodigo.Text))) Then
lista.codigo = Trim(TCodigo.Text)
Else
ErrorProvider1.SetError(TCodigo, "Codigo")
End If

If (Not (String.IsNullOrEmpty(TNombres.Text))) Then


lista.nombres = TNombres.Text
Else
ErrorProvider1.SetError(TNombres, "Nombres")
End If

If (Not (String.IsNullOrEmpty(TCargo.Text))) Then


lista.cargo = TCargo.Text
Else
ErrorProvider1.SetError(TCargo, "Cargo")
End If

If (Not (String.IsNullOrEmpty(TJefe.Text))) Then


lista.jefe = TJefe.Text
Else
ErrorProvider1.SetError(TJefe, "Jefe")
End If

If (Not (String.IsNullOrEmpty(TDepartamento.Text))) Then


lista.departamento = TDepartamento.Text
Else
ErrorProvider1.SetError(TDepartamento, "Departamento")
End If

If objnegocio.IngresarDatos(lista) = True Then


MessageBox.Show("datos agregados exitosamente")
cargar()
Else
MessageBox.Show("Datos no se agregaron")
End If

End Sub

Private Sub BModificar_Click_1(sender As System.Object,


e As System.EventArgs) HandlesBModificar.Click
Dim lista As New Clase_Empleado

lista.codigo = CStr(DataGridView1.CurrentRow.Cells(0).Value)

If (Not (String.IsNullOrEmpty(TNombres.Text))) Then


lista.nombres = TNombres.Text
Else
ErrorProvider1.SetError(TNombres, "Nombres")
End If

If (Not (String.IsNullOrEmpty(TCargo.Text))) Then


lista.cargo = TCargo.Text
Else
ErrorProvider1.SetError(TCargo, "Cargo")
End If

If (Not (String.IsNullOrEmpty(TJefe.Text))) Then


lista.jefe = TJefe.Text
Else
ErrorProvider1.SetError(TJefe, "Jefe")
End If

If (Not (String.IsNullOrEmpty(TDepartamento.Text))) Then


lista.departamento = TDepartamento.Text
Else
ErrorProvider1.SetError(TDepartamento, "Departamento")
End If

If objnegocio.ModificarDatos(lista) = True Then


MessageBox.Show("Datos se modificaron exitosamente")
cargar()
Else
MessageBox.Show("Datos no se modificaron")
End If
End Sub

Private Sub BEliminar_Click_1(sender As System.Object,


e As System.EventArgs) HandlesBEliminar.Click
Dim codigo As String = CStr(DataGridView1.CurrentRow.Cells(0).Value)
If objnegocio.EliminarDatos(codigo) = True Then
MessageBox.Show("Registro eliminado")
cargar()
Else
MessageBox.Show("registro no fue eliminado")
End If
End Sub

End Class

eso es todo :)

También podría gustarte