1. Proyecto Ado .NET<br />Mantenimiento de Clientes<br />El propósito de dicho manual es, demostrar la gran versatilidad que tiene el Ado .Net de Visual Basic, en relación a conexiones y ejecución de comandos, incluyendo la carga de DataSets, las operaciones básicas como: Inserciones, Eliminaciones de tipo lógico y Actualizaciones, demostrando la autogeneración de códigos para los clientes, pero antes debemos contar con un modelo relacional demostrativo. para tener un mayor alcance de lo que se esta realizando:<br />Se tiene el siguiente Modelo Relacional:<br />18415-2540<br />Dicho Script deberá ser ejecutado en el motor de base de datos de SQL Server.<br />El proyecto esta constituido por un formulario y un módulo, para elementos generales:<br />228601905<br />Este formulario esta constituido por cajas de texto (8), combos (4), picturebox (1) y un objeto openfiledialog (1) para control de imágenes.<br />El proyecto esta programado en el siguiente orden:<br />AGREGAR UN MODULO A NUESTRO PROYECTO, ESTE CONTENDRA LA DECLARACION PUBLICA DE UN DATASET (DsSysAdoNet) Y UN DATAADAPTER (DaGenerador) incluyendo la CONEXIÓN, PARA LA TABLA GENERADOR DE CODIGOS, PROGRAMELO DE LA SIGUENTE MANERA:Module Module1 Public DsSysAdoNet As New DataSet Public CN As New SqlClient.SqlConnection(\"
SERVER=LOCALHOST;UID=SA;” _ ”PASSWORD=123;DATABASE=SysAdoNet\"
) Public DaGenerador As New SqlClient.SqlDataAdapter(\"
select * from GENERADOR\"
, CN)Public Function GENERAR_CODIGO(ByVal TABLA As String) As String Dim Nfila, CEROS As Integer Dim ULT As Integer Dim CG As String = \"
\"
DaGenerador.Fill(DsSysAdoNet, \"
Generador\"
) DsSysAdoNet.Tables(\"
Generador\"
).DefaultView.Sort = \"
Parametro\"
Nfila = DsSysAdoNet.Tables(\"
Generador\"
).DefaultView.Find(TABLA) If Nfila >= 0 Then ULT = Val(DsSysAdoNet.Tables(\"
Generador\"
).Rows(Nfila)(1)) + 1 CEROS = 4 - Len(Trim(Str(ULT))) Select Case CEROS Case 3 : CG = Left(TABLA, 1) + \"
000\"
+ Trim(Str(ULT)) Case 2 : CG = Left(TABLA, 1) + \"
00\"
+ Trim(Str(ULT)) Case 1 : CG = Left(TABLA, 1) + \"
0\"
+ Trim(Str(ULT)) Case 0 : CG = Left(TABLA, 1) + Trim(Str(ULT)) End Select End If CN.Open() Dim SQL As String SQL = \"
UPDATE GENERADOR SET ULTIMO='\"
+ Str(ULT) + _ \"
' WHERE PARAMETRO='\"
+ TABLA + \"
'\"
Dim CMD As New SqlClient.SqlCommand(SQL, CN) CMD.CommandType = CommandType.Text CMD.ExecuteNonQuery() CN.Close() DsSysAdoNet.Tables(\"
Generador\"
).Rows.Clear() DaGenerador.Fill(DsSysAdoNet, \"
Generador\"
) GENERAR_CODIGO = CG End FunctionEnd Module<br />Abra el formulario y agregar los siguientes IMPORTACIONES.<br />Imports SYSTEM.DATAImports SYSTEM.DATA.SQLCLIENTImports SYSTEM.IOImports SYSTEM.DRAWING.IMAGINGEn el Public Class del Formulario, declare las siguientes variables, para uso exclusivo de nuestro formulario.Dim NOMBREARCHIVO As String = \"
\"
Dim CONDICION As String = \"
U\"
Dim FILA As IntegerDim DaCliente As New SqlClient.SqlDataAdapter(\"
select * from cliente\"
, CN)Dim DaIdentidad As New SqlClient.SqlDataAdapter(\"
select * from Identidad\"
, CN)Dim DaDistrito As New SqlClient.SqlDataAdapter(\"
Select * From distrito\"
, CN)En el formulario crear los siguientes procedimientos:Public Sub LimpiarObjetos() TextBox1.Text = \"
\"
: TextBox2.Text = \"
\"
: TextBox3.Text = \"
\"
TextBox4.Text = \"
\"
: TextBox5.Text = \"
\"
: TextBox6.Text = \"
\"
TextBox7.Text = \"
\"
: TextBox8.Text = \"
\"
ComboBox1.Text = \"
\"
: ComboBox2.Text = \"
\"
: ComboBox3.Text = \"
\"
ComboBox4.Text = \"
\"
End SubPublic Sub MostrarDatos()Dim EST As IntegerDim GEN As StringWith DsSysAdoNet.Tables(\"
Cliente\"
) Me.TextBox1.Text = IIf(IsDBNull(.Rows(FILA)(0)), \"
\"
, .Rows(FILA)(0)) Me.TextBox2.Text = IIf(IsDBNull(.Rows(FILA)(1)), \"
\"
, .Rows(FILA)(1)) GEN = IIf(IsDBNull(.Rows(FILA)(2)), \"
\"
, .Rows(FILA)(2)) Me.ComboBox1.Text = IIf(GEN = \"
M\"
, \"
Masculino\"
, \"
Femenino\"
) Me.ComboBox2.SelectedValue = \"
\"
Me.ComboBox2.SelectedValue = IIf(IsDBNull(.Rows(FILA)(3)), \"
\"
, .Rows(FILA)(3)) Me.TextBox3.Text = IIf(IsDBNull(.Rows(FILA)(4)), \"
\"
, .Rows(FILA)(4)) Me.ComboBox3.SelectedValue = \"
\"
ComboBox3.SelectedValue = IIf(IsDBNull(.Rows(FILA)(5)), \"
\"
, .Rows(FILA)(5)) Me.TextBox4.Text = IIf(IsDBNull(.Rows(FILA)(6)), \"
\"
, .Rows(FILA)(6)) Me.TextBox5.Text = IIf(IsDBNull(.Rows(FILA)(7)), \"
\"
, .Rows(FILA)(7)) Me.TextBox6.Text = IIf(IsDBNull(.Rows(FILA)(8)), \"
\"
, .Rows(FILA)(8)) Me.TextBox7.Text = IIf(IsDBNull(.Rows(FILA)(9)), \"
\"
, .Rows(FILA)(9)) Me.TextBox8.Text = IIf(IsDBNull(.Rows(FILA)(10)), \"
\"
, .Rows(FILA)(10)) EST = IIf(IsDBNull(.Rows(FILA)(11)), \"
\"
, .Rows(FILA)(11)) Me.ComboBox4.Text = IIf(EST = 1, \"
Habilitado\"
, \"
Inhabilitado\"
) If IsDBNull(.Rows(FILA).Item(12)) Then PictureBox1.Image = Nothing Else Dim VALOR As Byte() = CType(.Rows(FILA).Item(12), Byte()) Dim MEMORIA As New MemoryStream(VALOR) Dim MAPABITS As New Bitmap(MEMORIA) PictureBox1.Image = MAPABITS VALOR = Nothing End IfEnd WithEnd SubPROGRAMAR EN EL EVENTO LOAD DEL FORMULARIO LO SIGUIENTE: DaCliente.Fill(DsSysAdoNet, \"
Cliente\"
) DaIdentidad.Fill(DsSysAdoNet, \"
Identidad\"
) DaDistrito.Fill(DsSysAdoNet, \"
Distrito\"
) 'Carga de Combo Generos ComboBox1.Items.Add(\"
Masculino\"
) ComboBox1.Items.Add(\"
Femenino\"
) 'Carga de combo Identidad ComboBox2.DataSource = DsSysAdoNet.Tables(\"
Identidad\"
) ComboBox2.DisplayMember = \"
Descripcion_id\"
ComboBox2.ValueMember = \"
Codigo_Id\"
'Carga del combo Distrito ComboBox3.DataSource = DsSysAdoNet.Tables(\"
Distrito\"
) ComboBox3.DisplayMember = \"
DesDistrito\"
ComboBox3.ValueMember = \"
IdDistrito\"
'Carga del combo Estado ComboBox4.Items.Clear() ComboBox4.Items.Add(\"
Habilitado\"
) ComboBox4.Items.Add(\"
Inhabilitado\"
) Call LimpiarObjetos() Call MostrarDatos()PROGRAMAR EL BOTON DE DESPLAZAMIENTO IZQUIERDA INICIO (<<) Button1_ClickDim Contador As Integer = DsSysAdoNet.Tables(\"
Cliente\"
).Rows.Count + 1If Contador < 0 Then Return FILA = 0 Call MostrarDatos()PROGRAMAR EL BOTON DE DESPLAZAMIENTO A LA IZQUIERDA (<) Button2_ClickDim Contador As Integer = DsSysAdoNet.Tables(\"
Cliente\"
).Rows.CountIf Contador < 0 Then Return FILA -= 1 If FILA < 0 Then FILA = 0 Call MostrarDatos()PROGRAMAR EL BOTON DE DESPLAZAMIENTO A LA DERECHA (>) Button3_ClickDim Contador As Integer = DsSysAdoNet.Tables(\"
Cliente\"
).Rows.Count If Contador < 0 Then Return FILA += 1 If FILA >= Contador Then FILA = Contador - 1 Call MostrarDatos()PROGRAMAR EL BOTON DE DESPLAZAMIENTO A LA DERECHA FINAL (>>) Button4_ClickDim Contador As Integer = DsSysAdoNet.Tables(\"
Cliente\"
).Rows.Count - 1 If Contador < 0 Then Return FILA = Contador Call MostrarDatos()PROGRAMANDO EL BOTON Nuevo / Cancelar Button5_Click If Button5.Text = \"
Nuevo\"
Then Button5.Text = \"
Cancelar\"
CONDICION = \"
I\"
Call LimpiarObjetos() TextBox2.Focus() Else Button5.Text = \"
Nuevo\"
CONDICION = \"
U\"
Call MostrarDatos() End IfPROGRAMANDO EL BOTON Consultar Button6_Click Dim NR As Integer DsSysAdoNet.Tables(\"
Cliente\"
).DefaultView.Sort = \"
COD_CLI\"
NR = DsSysAdoNet.Tables(\"
Cliente\"
).DefaultView.Find(TextBox1.Text) If NR >= 0 Then FILA = NR Call MostrarDatos() Else MsgBox(\"
El Cliente no Existe...\"
) End IfPROGRAMANDO EL BOTON Eliminar Button7_ClickIf MsgBox(\"
Eliminar\"
, MsgBoxStyle.OkCancel, \"
Esta Seguro?\"
) = MsgBoxResult.Ok Then CN.Open() Dim SQL As String SQL = \"
UPDATE CLIENTE SET ESTADO=0 WHERE COD_CLI='\"
+ TextBox1.Text + \"
'\"
Dim CMD As New SqlClient.SqlCommand(SQL, CN) CMD.CommandType = CommandType.Text CMD.ExecuteNonQuery() CN.Close() DsSysAdoNet.Tables(\"
CLIENTE\"
).Rows.Clear() DaCliente.Fill(DsSysAdoNet, \"
Cliente\"
) Call MostrarDatos()End IfPROGRAMANDO EL BOTON Actualizar Button8_Click'ALMACENANDO DE DATOS Dim SEX As String = \"
\"
Dim EST As IntegerDim SQL As String = \"
\"
SEX = IIf(ComboBox1.Text = \"
Masculino\"
, \"
M\"
, \"
F\"
)EST = IIf(ComboBox4.Text = \"
Habilitado\"
, 1, 0)If CONDICION = \"
I\"
Then TextBox1.Text = GENERAR_CODIGO(\"
CLIENTE\"
) SQL = \"
INSERT INTO CLIENTE VALUES('\"
+ TextBox1.Text + \"
','\"
+ _ TextBox2.Text + \"
','\"
+ SEX + \"
','\"
+ ComboBox2.SelectedValue + \"
','\"
+ _ TextBox3.Text + \"
','\"
+ ComboBox3.SelectedValue + \"
','\"
+ TextBox4.Text + \"
','\"
+ _ TextBox5.Text + \"
','\"
+ TextBox6.Text + \"
','\"
+ TextBox7.Text + \"
','\"
+ _ TextBox8.Text + \"
','\"
+ Str(EST) + \"
',null)\"
End IfIf CONDICION = \"
U\"
Then SQL = \"
UPDATE CLIENTE SET NOMCLI='\"
+ TextBox2.Text + \"
',SEXO='\"
+ SEX + \"
',\"
+ _ \"
CODIGO_ID='\"
+ ComboBox2.SelectedValue + \"
',NUMERO_ID='\"
+ TextBox3.Text + \"
',\"
+ _ \"
IDDISTRITO='\"
+ ComboBox3.SelectedValue + \"
',TELEFONO='\"
+ TextBox4.Text + \"
',\"
+ _ \"
DIRECCION='\"
+ TextBox5.Text + \"
',RUC_CLIENTE='\"
+ TextBox6.Text + \"
',\"
+ _ \"
FECHA_NAC='\"
+ TextBox7.Text + \"
',FECHA_REG='\"
+ TextBox8.Text + \"
',\"
+ _ \"
ESTADO='\"
+ Str(EST) + \"
' WHERE COD_CLI='\"
+ TextBox1.Text + \"
'\"
End If CN.Open() Dim CMD As New SqlClient.SqlCommand(SQL, CN) CMD.CommandType = CommandType.Text CMD.ExecuteNonQuery() CN.Close() DsSysAdoNet.Tables(\"
CLIENTE\"
).Rows.Clear() DaCliente.Fill(DsSysAdoNet, \"
Cliente\"
) Call MostrarDatos()PROGRAMANDO EL BOTON Filtros Button9_Click 'Este boton nos conduce a otro formulario (form2) Form2.Show()PROGRAMANDO EL BOTON Examinar Button10_ClickWith OpenFileDialog1 .Filter = \"
(ARCHIVOS JPG) *.JPG |*.JPG\"
.InitialDirectory = \"
C:\Documents and “ + _ “Settings\LordSerafan\Escritorio\AdoNet\SysCliente\” + _ “WindowsApplication1\Fotos\"
.Title = \"
FOTOS DEL ALUMNO\"
If (.ShowDialog = Windows.Forms.DialogResult.OK) Then NOMBREARCHIVO = .FileName PictureBox1.Image = Image.FromFile(NOMBREARCHIVO) End IfEnd WithPROGRAMANDO EL BOTON Grabar … Guardando foto a la BD Button11_ClickDim FSFOTO As New FileStream(NOMBREARCHIVO, FileMode.Open, FileAccess.Read) Dim INFOFOTO As FileInfo = New FileInfo(NOMBREARCHIVO) Dim TEMPORAL As Long = INFOFOTO.Length Dim LONGITUD As Long = Convert.ToInt32(TEMPORAL) Dim IMAGEN(LONGITUD) As Byte FSFOTO.Read(IMAGEN, 0, LONGITUD) FSFOTO.Close() CN.Open() Dim DAFOTO As New SqlDataAdapter DAFOTO.SelectCommand = New SqlCommand With DAFOTO.SelectCommand .Connection = CN .CommandType = CommandType.StoredProcedure .CommandText = \"
Grabar_Foto\"
.Parameters.Add(New SqlParameter(\"
@Ccli\"
, SqlDbType.Char, 7, _ ParameterDirection.Input)).Value = TextBox1.Text .Parameters.Add(New SqlParameter(\"
@Fot\"
, SqlDbType.Image, LONGITUD, _ ParameterDirection.Input)).Value = IMAGEN .ExecuteNonQuery End With CN.Close() DsSysAdoNet.Tables(\"
CLIENTE\"
).Rows.Clear() DaCliente.Fill(DsSysAdoNet, \"
Cliente\"
) Call MostrarDatos()<br />AL EJECUTAR EL FORMULARIO, TENDRA EL SIGUIENTE ASPECTO:<br />18415-6985<br />Nota: Cuando se proceda a insertar a un nuevo cliente, procurar no grabar la foto, después de insertar el registro, proceda a buscar la foto con el botón EXAMINAR, cuando haya sido seleccionada la foto proceda a GRABAR.<br />Diseñe el siguiente formulario (Filtros) cuyo fin será el de filtrar datos.<br />3810148590<br />Este formulario permitirá filtrar a los clientes por sus apellidos y nombres completos o carácter por carácter.<br />Imports System.Data.SqlClientPublic Class Form4Dim DsEntorno As New DataSetPrivate Sub TextBox1_TextChanged Dim DaCli As SqlDataAdapter DaCli = Clases.DevolverClientesFiltrados(\"
*\"
) DaCli.Fill(DsEntorno, \"
Filtro\"
) If DsEntorno.Tables(\"
Filtro\"
).Rows.Count >= 0 Then DsEntorno.Tables(\"
Filtro\"
).Rows.Clear() DaCli = Clases.DevolverClientesFiltrados(TextBox1.Text) DaCli.Fill(DsEntorno, \"
Filtro\"
) DataGrid1.DataSource = DsEntorno.Tables(\"
Filtro\"
) End If<br />