Está en la página 1de 20

PEDIDO

1
Añadimos una nueva columna IdTrabajador Con la consulta
alter table DETALLE_VENTA
add IdTrabajador int

2
TRABAJADOR

Si un cliente se elimina tb se elimina las ventas


Click en INSERT And UPDATE Specificat
En Delete Rule ponemos en Cascade

3
Se aplica la regla de eliminación

Si aplicamos la regla de eliminación en cascada


4
No aplicamos la regla

5
No aplicamos la regla de eliminación

Diagrama de la base de datos TONY

Código de conexión
Imports System.Data.SqlClient

Public Class conexion

Protected cnn As New SqlConnection

Public idusuario As Integer

Protected Function conectado()


Try
cnn = New SqlConnection("Data Source=EQUIPO;Initial Catalog=TONY;User ID=sa;Password=root")
cnn.Open()
Return True
Catch ex As Exception
MsgBox(ex.Message)
Return False

6
End Try
End Function

Protected Function desconectado()


Try
If cnn.State = ConnectionState.Open Then
cnn.Close()
Return True
Else
Return False
End If
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
End Function
End Class

Creamos la clase fcliente


Imports System.Data.SqlClient

Public Class fcliente

Inherits conexion
Dim cmd As New SqlCommand

Public Function mostrar() As DataTable


Try
conectado()
cmd = New SqlCommand("mostrar_cliente")
cmd.CommandType = CommandType.StoredProcedure

cmd.Connection = cnn

If cmd.ExecuteNonQuery Then
Dim dt As New DataTable
Dim da As New SqlDataAdapter(cmd)
da.Fill(dt)
Return dt
Else
Return Nothing
End If
Catch ex As Exception
MsgBox(ex.Message)
Return Nothing
Finally
desconectado()
End Try
End Function

End Class

Creamos el procedimiento almacenado mostrar_cliente


create proc mostrar_cliente
as
select * from CLIENTE order by IdCliente desc
go

7
creamos el formulario frmcliente

Codigo frmcliente

Public Class frmcliente

Private dt As New DataTable

Private Sub frmcliente_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


MyBase.Load

mostrar()

End Sub

Private Sub mostrar()

Try
Dim func As New fcliente
dt = func.mostrar
datalistado.Columns.Item("Eliminar").Visible = False

If dt.Rows.Count <> 0 Then


datalistado.DataSource = dt
txtBuscar.Enabled = True
datalistado.ColumnHeadersVisible = False
Inexistente.Visible = False
Else
datalistado.DataSource = Nothing
txtBuscar.Enabled = False
datalistado.ColumnHeadersVisible = False
Inexistente.Visible = True
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try

8
btnNuevo.Visible = True
btnEditar.Visible = False

buscar()

End Sub

Private Sub buscar()


Try
Dim ds As New DataSet
ds.Tables.Add(dt.Copy)
Dim dv As New DataView(ds.Tables(0))

dv.RowFilter = cboCampo.Text & "like '" & txtBuscar.Text & "% '"

If dv.Count <> 0 Then


Inexistente.Visible = False
datalistado.DataSource = dv
ocultar_columnas()

Else
Inexistente.Visible = True
datalistado.DataSource = Nothing
End If

Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Private Sub ocultar_columnas()


datalistado.Columns(1).Visible = False
End Sub

Creamos una clave para el botón Nuevo y Editar

En la carpeta Lógica insertamos una clase con el botón vcliente

Public Class vcliente

Dim IdCliente As Integer


Dim Nombre, Apellidos, Direccion, Telefono, Celular, CI As String

'seeter y getter

Public Property gIdCliente


Get
Return IdCliente
End Get
Set(ByVal value)
IdCliente = value
End Set
End Property

Public Property gNombre


Get
Return Nombre
End Get
Set(ByVal value)

9
Nombre = value
End Set
End Property

Public Property gApellidos


Get
Return Apellidos
End Get
Set(ByVal value)
Apellidos = value
End Set
End Property

Public Property gDireccion


Get
Return Direccion
End Get
Set(ByVal value)
Direccion = value
End Set
End Property

Public Property gTelefono


Get
Return Telefono
End Get
Set(ByVal value)
Telefono = value
End Set
End Property

Public Property gCelular


Get
Return Celular
End Get
Set(ByVal value)
Celular = value
End Set
End Property

Public Property gCI


Get
Return CI
End Get
Set(ByVal value)
CI = value
End Set
End Property

'constructores

Public Sub New()

End Sub

Public Sub New(ByVal IdCliente As Integer, ByVal Nombre As String, ByVal Apellidos As String, ByVal
Direccion As String, ByVal Telefono As String, ByVal Celular As String, ByVal CI As String)

gIdCliente = IdCliente
gNombre = Nombre
gApellidos = Apellidos
gDireccion = Direccion

10
gTelefono = Telefono
gCelular = Celular
gCI = CI

End Sub
End Class
En SQL hacemos el procedimiento almacenado insertar_cliente
create proc insertar_cliente
@Nombre varchar (50),
@Apellidos varchar (50),
@Direccion varchar (100),
@Telefono varchar (8),
@Celular varchar (8),
@CI varchar (8)
as
insert into CLIENTE (Nombre,Apellidos,Direccion,Telefono,celular,CI) values
(@Nombre,@Apellidos,@Direccion,@Telefono,@celular,@CI)
Go

Volvemos a Visual Basic y creamos una función que nos permita Insertar y Enviar datos desde Visual a SQL

Abrimos la función fCLIENTE y creamos otra función de bajo de la función mostrar

Creamos la función INSERTAR_CLIENTE

Public Function insertar(ByVal dts As vcliente) As Boolean

Try
conectado()
cmd = New SqlCommand("insertar_cliente")
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = cnn

cmd.Parameters.AddWithValue("@Nombre", dts.gNombre)
cmd.Parameters.AddWithValue("@Apellidos", dts.gApellidos)
cmd.Parameters.AddWithValue("@Direccion", dts.gDireccion)
cmd.Parameters.AddWithValue("@Telefono", dts.gTelefono)
cmd.Parameters.AddWithValue("@Celular", dts.gCelular)
cmd.Parameters.AddWithValue("@CI", dts.gCI)

If cmd.ExecuteNonQuery Then
Return True
Else
Return False
End If

Catch ex As Exception
MsgBox(ex.Message)
Return False
Finally
desconectado()
End Try
End Function

Volvemos a frmCLIENTE y añadimos un ErrorProviter (permite capturar algunos errores)

Podemos cambiar el nombre a erroricono


11
Empezamos a programar cada caja de texto

Y cambiamos TextChanged por Validating ya que empezaremos a validar

Private Sub txtNombre_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


txtNombre.TextChanged

End Sub

Private Sub txtNombre_Validating(ByVal sender As Object, ByVal e As


System.ComponentModel.CancelEventArgs) Handles txtNombre.Validating

If DirectCast(sender, TextBox).Text.Length > 0 Then


Me.erroricono.SetError(sender, "")
Else
Me.erroricono.SetError(sender, "Datos Obligatorios")
End If
End Sub

12
Private Sub txtApellidos_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles txtApellidos.TextChanged

End Sub

Private Sub txtApellidos_Validating(ByVal sender As Object, ByVal e As


System.ComponentModel.CancelEventArgs) Handles txtApellidos.Validating

If DirectCast(sender, TextBox).Text.Length > 0 Then


Me.erroricono.SetError(sender, "")
Else
Me.erroricono.SetError(sender, "Datos Obligatorios")
End If
End Sub

Private Sub txtDireccion_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles txtDireccion.TextChanged

End Sub

Private Sub txtDireccion_Validating(ByVal sender As Object, ByVal e As


System.ComponentModel.CancelEventArgs) Handles txtDireccion.Validating

If DirectCast(sender, TextBox).Text.Length > 0 Then


Me.erroricono.SetError(sender, "")
Else
Me.erroricono.SetError(sender, "Datos Obligatorios")
End If
End Sub

Private Sub txtCI_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


txtCI.TextChanged

End Sub

Private Sub txtCI_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs)


Handles txtCI.Validating

If DirectCast(sender, TextBox).Text.Length > 0 Then


Me.erroricono.SetError(sender, "")
Else
Me.erroricono.SetError(sender, "Datos Obligatorios")
End If
End Sub

Creamos el botón Guardar y lo ponemos subre el botón Editar eso será controlado mediante código

Creamos un procedimiento llamado limpiar dentro del frmcliente que se encuentra al medio de…
mostrar()

End Sub

Public Sub limpiar()

btnGuardar.Visible = True
btnEditar.Visible = False

txtNombre.Text = ""

13
txtApellidos.Text = ""
txtDireccion.Text = ""
txtTelefono.Text = ""
txtCelular.Text = ""
txtCI.Text = ""
txtIdCliente.Text = ""

End Sub

Private Sub mostrar()

El código limpiar lo llamanos desde el botón Nuevo

Private Sub btnNuevo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


btnNuevo.Click

limpiar()
mostrar()

End Sub

El código del botón Guardar


Private Sub btnGuardar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnGuardar.Click

If Me.ValidateChildren = True And txtNombre.Text <> "" And txtApellidos.Text <> "" And
txtDireccion.Text <> "" And txtTelefono.Text <> "" And txtCelular.Text <> "" And txtCI.Text <> "" Then
Try
Dim dts As New vcliente
Dim func As New fcliente

dts.gNombre = txtNombre.Text
dts.gApellidos = txtApellidos.Text
dts.gDireccion = txtDireccion.Text
dts.gTelefono = txtTelefono.Text
dts.gCelular = txtCelular.Text
dts.gCI = txtCI.Text

If func.insertar(dts) Then
MessageBox.Show("Cliente Registrado Correctamente", "Guardando Registro",
MessageBoxButtons.OK, MessageBoxIcon.Information)
mostrar()
limpiar()
Else
MessageBox.Show("Cliente No Fue Registrado Correctamente", "Intente de Nuevo",
MessageBoxButtons.OK, MessageBoxIcon.Error)
mostrar()
limpiar()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Else
MessageBox.Show("Falta Ingresar Algunos Datos", "Intente de Nuevo", MessageBoxButtons.OK,
MessageBoxIcon.Information)
End If
End Sub

Para el botón Editar creamos un procedimiento almacenado en la base de datos


14
create proc editar_cliente
@IdCliente integer,
@Nombre varchar(50),
@Apellidos varchar(50),
@Direccion varchar(100),
@Telefono varchar(8),
@celular varchar(8),
@DNI varchar(8)
as
update CLIENTE set
Nombre=@Nombre,Apellidos=@Apellidos,Direccion=@Direccion,Telefono=@Telefono,celular=@celular
,CI=@CI
where IdCliente=@IdCliente

go

volvemos a Visual

doble click en el DataGridView

cambiamos el CellContentClick por CellClick

Escribimos el código
Private Sub datalistado_CellClick(ByVal sender As Object, ByVal e As
System.Windows.Forms.DataGridViewCellEventArgs) Handles datalistado.CellClick

txtIdCliente.Text = datalistado.SelectedCells.Item(1).Value
txtNombre.Text = datalistado.SelectedCells.Item(2).Value
txtApellidos.Text = datalistado.SelectedCells.Item(3).Value
txtDireccion.Text = datalistado.SelectedCells.Item(4).Value
txtTelefono.Text = datalistado.SelectedCells.Item(5).Value
txtCelular.Text = datalistado.SelectedCells.Item(6).Value
txtCI.Text = datalistado.SelectedCells.Item(7).Value

btnEditar.Visible = True
btnGuardar.Visible = False

End Sub

Private Sub datalistado_CellContentClick(ByVal sender As System.Object, ByVal e As


System.Windows.Forms.DataGridViewCellEventArgs) Handles datalistado.CellContentClick

End Sub

15
Volvemos a la función fcliente

Empezamos a hacer el código editar


Public Function editar(ByVal dts As vcliente) As Boolean
Try
conectado()
cmd = New SqlCommand("editar_cliente")
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = cnn

cmd.Parameters.AddWithValue("@IdCliente", dts.gIdCliente)
cmd.Parameters.AddWithValue("@Nombre", dts.gNombre)
cmd.Parameters.AddWithValue("@Apellidos", dts.gApellidos)
cmd.Parameters.AddWithValue("@Direccion", dts.gDireccion)
cmd.Parameters.AddWithValue("@Telefono", dts.gTelefono)
cmd.Parameters.AddWithValue("@celular", dts.gcelular)
cmd.Parameters.AddWithValue("@CI", dts.gCI)

If cmd.ExecuteNonQuery Then
Return True
Else
Return False
End If
Catch ex As Exception
MsgBox(ex.Message)
Return False
Finally
desconectado()
End Try
End Function

Volvemos a frmcliente

Click en el botón editar


Private Sub btnEditar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnEditar.Click

Dim result As DialogResult

result = MessageBox.Show("Decea Editar los Datos del Cliente?", "Modificando Registros",


MessageBoxButtons.OKCancel, MessageBoxIcon.Question)

If result = DialogResult.OK Then

If Me.ValidateChildren = True And txtNombre.Text <> "" And txtApellidos.Text <> "" And
txtDireccion.Text <> "" And txtTelefono.Text <> "" And txtCelular.Text <> "" And txtCI.Text <> "" And
txtIdCliente.Text <> "" Then

Try
Dim dts As New vcliente
Dim func As New fcliente

dts.gIdCliente = txtIdCliente.Text
dts.gNombre = txtNombre.Text
dts.gApellidos = txtApellidos.Text
dts.gDireccion = txtDireccion.Text
dts.gTelefono = txtTelefono.Text

16
dts.gcelular = txtCelular.Text
dts.gCI = txtCI.Text

If func.editar(dts) Then
MessageBox.Show("Cliente Modificado Correctamente", "Modificando Registro",
MessageBoxButtons.OK, MessageBoxIcon.Information)
mostrar()
limpiar()
Else
MessageBox.Show("Cliente no fue Modificado", "Intente de Nuevo",
MessageBoxButtons.OK, MessageBoxIcon.Error)
mostrar()
limpiar()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Else
MessageBox.Show("Falta Ingresar Algunos Datos", "Intente de Nuevo", MessageBoxButtons.OK,
MessageBoxIcon.Information)
End If
End If

End Sub

Creamos el procedimiento almacenado eliminar_cliente


create proc eliminar_cliente
@IdCliente integer
as
delete from CLIENTE where IdCliente=@IdCliente
go

volvemos a Visual y en la función fcliente realizamos el siguiente codigo para


eliminar_cliente

Public Function eliminar(ByVal dts As vcliente) As Boolean

Try
conectado()
cmd = New SqlCommand("eliminar_cliente")
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = cnn

cmd.Parameters.Add("IdCliente", SqlDbType.NVarChar, 50).Value = dts.gIdCliente

If cmd.ExecuteNonQuery Then
Return True
Else
Return False
End If
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
End Function

17
Volvemos al frmcliente

Codificaremos para poder eliminar varios reguistros a la vez. Agregamos un CheckBox y


ponemos como nombre cbEliminar y el text ponemos Eliminar

Click en el DataCridView en sus propiedades seleccionamos Columns

Click en Agregar..

Click en Tipo seleccionamos

Y Agregar

En el frmcliente doble click en el cbEliminar y escribimos el código

Private Sub cbEliminar_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


cbEliminar.CheckedChanged

If cbEliminar.CheckState = CheckState.Checked Then


dataListado.Columns.Item("eliminar").Visible = True
Else
dataListado.Columns.Item("eliminar").Visible = False
End If
18
End Sub
Doble click en el DataGridView

Private Sub dataListado_CellContentClick(ByVal sender As System.Object, ByVal e As


System.Windows.Forms.DataGridViewCellEventArgs) Handles dataListado.CellContentClick

If e.ColumnIndex = Me.dataListado.Columns.Item("Eliminar").Index Then


Dim chkcell As DataGridViewCheckBoxCell = Me.dataListado.Rows(e.RowIndex).Cells("Eliminar")
chkcell.Value = Not chkcell.Value
End If
End Sub

Doble click sobre el botón Eliminar y escribimos el siguiente código

Private Sub btnEliminar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


btnEliminar.Click

Dim result As DialogResult


result = MessageBox.Show("Desea Eliminar los Clientes Seleccionados?", "Eliminando Clientes",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question)

If result = DialogResult.OK Then


Try
For Each row As DataGridViewRow In dataListado.Rows
Dim marcado As Boolean = Convert.ToBoolean(row.Cells("Eliminar").Value)

If marcado Then
Dim onekey As Integer = Convert.ToInt32(row.Cells("IdCliente").Value)
Dim vdb As New vCLIENTE
Dim func As New fCLIENTE
vdb.gIdCliente = onekey
If func.eliminar(vdb) Then
Else
MessageBox.Show("Cliente No Fue Eliminado", "Intente de Nuevo",
MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End If
Next
Call mostrar()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Else
MessageBox.Show("Cancelando Eliminación", "Cancelado", MessageBoxButtons.OK,
MessageBoxIcon.Information)
Call mostrar()
End If
Call limpiar()
End Sub
End Class

19
20

También podría gustarte