September 30, 2022 | Author: Anonymous | Category: N/A
Download 368338-MANUAL de VISUAL BASIC Segunda Parte...
MANUAL DE VISUAL BASIC PARTE II
CONSULTAS CON SQL – REPORTING SERVICES
Nombre: Karen Johana Estrada Aguilar
CAJAMARCA, 2012
Manual de Visual Basic Parte II 2012 2012 INDICE
CONSULTAS CON SQL EN VISUAL BASIC ........................................................................ 2 Mostrar el registro de la tabla estudiantes: ...................................................... ................................................................ .......... 4 Realizar el ejercicio anterior en una página web: ................................................... ...................................................... ... 5 Buscar un alumno filtrado por su código con Radio button: ...................................... 8 Buscar un alumno filtrado por su código con Enter en el Textbox:.......................... 10 Mostrar alumnos o alumnas con radios button ................................................. ......................................................... ........ 12 UN TOOLsTRIP CON IMÁGENES .................................................. ...................................................................................... .................................... 15 El menúStrip deberá estar acompañado de imágenes: imágen es: .................................................... .......................................... .......... 15 Creamos un módulo (Globales) ............................................... ............................................................................................ ............................................. 16 AGREGAR UNA CONSULTA A UN LISTBOX .................................................. .................................................................... .................. 19 EJERCICIOS COMPLEMENTARIOS SOBRE CONSULTAS A BASE DE DATOS USANDO VISUAL BASIC 2010 ........................................................................................... 32 EJERCICIOS ................................................ ...................................................................................................... ........................................................................ .................. 47 INSERTAR EN UNA TABLA DE UBA BASE DE DATOS DESDE VISUAL BASIC ........... 59 OBJETO MaskedTextBox ..................................................................................................... .......................................................................... ........................... 60 CONSULTAR, AGREGAR Y ELIMINAR REGISTROS EN LA TABLA CATEGORÍAS ...... 69 CREAR IN INICIO DE SESIÓN PARA EL SISTEMA .................................................. .......................................................... ........ 79 Cambiar contraseña desde otro formulario .......................................... ..................................................................... ........................... 82 CREANDO EL SISTEMA DE ASISTENCIA DE LOS ALUMNOS DE INGENIERÍA DE SISTEMAS A LA XII SEMANA SI SISTÉMICA STÉMICA ...................................................... ........................................................................ .................. 85 REPORTING SERVICE ................................................... ....................................................................................................... ...................................................... 94
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
1
Manual de Visual Basic Parte II 2012 2012
CONSULTAS CON SQL EN VISUAL BASIC Para hacer una consulta desde Visual Studio a una base de datos hacemos: hacemos:
Primero creamos una tabla Estudiantes en Sql Sever Managament
Pasamos los registros de los alumnos en un documento Csv (separado por comas), ejecutando la siguiente consulta:
use Asistencia_Semana_Sistémica use bulk insert dbo insert dbo..PARTICIPANTES from 'I:\alumnos2.csv' from with ( fieldterminator==',' fieldterminator ',',, --separa a los campos, cambia de campo rowterminator=='\n' rowterminator '\n' -- cambia de filas por el enter )
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
2
Manual de Visual Basic Parte II 2012 2012
CREAMOS UN FORMULARIO EN VISUAL STUDIO
Ponemos la cabecera que funcionaría f uncionaría como una biblioteca: Imports Imports System.Data.SqlClient Realizamos la conexión a la Base de Datos creando el objeto conex (conex es un objeto que guarda la ubicación de la base de datos ya sabe dónde está, es un camino)
Dim conex As New SqlConnection SqlConnection(("server=.;database=Northwind;trusted_connection=true" "server=.;database=Northwind;trusted_connection=true"))
Hacemos una consulta con SQLDataAadapter Dim Dim datos datos As As New New SqlDataAdapter( SqlDataAdapter("select* from EMPLOYEES", EMPLOYEES", conex)
Creamos un objeto DataSet Dim ds ds As As New Data. New Data.DataSet DataSet Dim
Llenamos los registros obtenidos por la consulta en un DataGridView
datos.Fill(ds, "Alumnos") "Alumnos") DGV1.DataSource = ds.Tables("Alumnos" ds.Tables("Alumnos"))
El código en Visual Studio es:
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
3
Manual de Visual Basic Parte II 2012 2012
Ejemplo:
Mostrar el registro de la tabla estudiantes:
Imports System.Data.SqlClient Imports System.Data.SqlClient Public Class Public Class Form1 Form1 Private Sub Form1_Load(sender Form1_Load(sender As As System. System.Object Object,, e As As System. System.EventArgs EventArgs)) Handles Handles Private Sub MyBase.Load MyBase.Load Dim Dim conex conex As As New New SqlConnection(("server=MIK3\io;database=Northwind1;trusted_connection=true" "server=MIK3\io;database=Northwind1;trusted_connection=true")) 'conex es un SqlConnection objeto que guarda la ubicacion de la base de datos ya sabe donde esta, es un camino camino Dim datos datos As As New New SqlDataAdapter( SqlDataAdapter("select* from Estudiante" Estudiante",, conex) Dim Dim ds As New Data. New Data.DataSet DataSet Dim ds As datos.Fill(ds, "Alumnos" "Alumnos")) DGV1.DataSource = ds.Tables("Alumnos" ds.Tables("Alumnos")) End Sub End Sub End Class Class End
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
4
Manual de Visual Basic Parte II 2012 2012
Realizar el ejercicio anterior en una página web:
1° Creamos un nuevo proyecto y escogemos en planillas instaladas la opción Web:
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
5
Manual de Visual Basic Parte II 2012 2012
2° Escogemos la opción Aplicación web ASP.NET:
3° Se observa el entorno así:
4° Agregamos un nuevo elemento un (Formulario):
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
6
Manual de Visual Basic Parte II 2012 2012
Escogemos un DataGridView y lo arrastramos sobre el formulario:
Escribimos el código:
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
7
Manual de Visual Basic Parte II 2012 2012
Cargó:
Buscar un alumno filtrado por su código con Radio button:
Consulta SQL: create proc create proc buscar_alumnos @id char @id char((10 10)) as select * select from Estudiante from where Id_estudiante= where Id_estudiante=@id Imports System.Data.SqlClient Imports System.Data.SqlClient Public Class Public Class Form1 Form1 Private Sub Button1_Click(sender Button1_Click(sender As As System. System.Object Object,, e As As System. System.EventArgs EventArgs)) Handles Handles Private Sub Button1.Click Dim conex As New New Dim conex As SqlConnection SqlConnection(("server=.;database=Northwind;trusted_connection=true" "server=.;database=Northwind;trusted_connection=true")) Dim Dim datos datos As As New New SqlDataAdapter( SqlDataAdapter("buscar_alumnos" "buscar_alumnos",, conex) Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
8
Manual de Visual Basic Parte II 2012 2012
Dim ds ds As As New Data. New Data.DataSet DataSet Dim CommandType.StoredProcedure .StoredProcedure '*** '*** datos.SelectCommand.CommandType = CommandType datos.SelectCommand.Parameters.Add("@id" datos.SelectCommand.Parameters.Add( "@id",, SqlDbType SqlDbType.Char, .Char, 10).Value = TextBox1.Text datos.Fill(ds, "alumnitos" "alumnitos")) = ds.Tables("Alumnitos" ds.Tables("Alumnitos")) EndDGV.DataSource End Sub Sub End End Class Class
Diseño del formulario:
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
9
Manual de Visual Basic Parte II 2012 2012
Buscar un alumno filtrado por su código con Enter en el Textbox:
En el evento keypress del textbox hacemos la conexión y el código:
Imports System.Data.SqlClient Imports System.Data.SqlClient Public Class Form2 Form2 Public Class Private Sub TextBox1_KeyPress(sender TextBox1_KeyPress(sender As As Object, Object, e As As Private Sub KeyPressEventArgs)) Handles Handles TextBox1.KeyPress TextBox1.KeyPress System.Windows.Forms.KeyPressEventArgs System.Windows.Forms. If e.KeyChar Then If e.KeyChar = Chr(13) Then Dim Dim conex conex As As New New SqlConnection( SqlConnection("server=.;database=Northwind;trusted_connection=true" "server=.;database=Northwind;trusted_connection=true")) Dim datos datos As As New New SqlDataAdapter SqlDataAdapter(("buscar_alumnos" "buscar_alumnos",, conex) Dim Dim ds Dim ds As As New Data. New Data.DataSet DataSet CommandType.StoredProcedure .StoredProcedure datos.SelectCommand.CommandType = CommandType datos.SelectCommand.Parameters.Add("@id" datos.SelectCommand.Parameters.Add( "@id",, SqlDbType SqlDbType.Char, .Char, 10).Value = TextBox1.Text datos.Fill(ds, "alumnitos") "alumnitos") DGV.DataSource = ds.Tables("Alumnitos" ds.Tables("Alumnitos")) TextBox1.Text = "" "" TextBox1.Focus() End If If End End Sub End Sub
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
10
Manual de Visual Basic Parte II 2012 2012
Private Sub Form2_Load(sender Form2_Load(sender As System. As System.Object Object,, e As System. As System.EventArgs EventArgs)) Handles Handles Private Sub MyBase.Load MyBase.Load TextBox1.Focus() End Sub End Sub Private Private Sub Sub TextBox1_TextChanged(sender TextBox1_TextChanged(sender As As System. System.Object Object,, e As As System. System.EventArgs EventArgs)) Handles Handles TextBox1.TextChanged TextBox1.TextChanged TextBox1.Focus() End Sub End Sub End End Class Class
Filtrar alumno por apellido: Imports Imports System.Data.SqlClient System.Data.SqlClient Public Public Class Class Form4 Form4 Private Private Sub Sub TextBox1_KeyPress( TextBox1_KeyPress(ByVal ByVal sender sender As As Object Object,, ByVal e ByVal e As As System.Windows.Forms.KeyPressEventArgs System.Windows.Forms. KeyPressEventArgs)) Handles Handles TextBox1.KeyPress TextBox1.KeyPress If e.KeyChar Then If e.KeyChar = Chr(13) Then Dim conex conex As As New New Dim SqlConnection("server=MIK3\io;database=Northwind1;trusted_connection=true" SqlConnection( "server=MIK3\io;database=Northwind1;trusted_connection=true")) Dim Dim datos datos As As New New SqlDataAdapter SqlDataAdapter(("apell" "apell",, conex) ' "selec * from Estudiante where Id_estudiante=@id" (la linea *** no seria) seria) Dim Dim ds ds As As New Data. New Data.DataSet DataSet CommandType.StoredProcedure .StoredProcedure '*** '*** datos.SelectCommand.CommandType = CommandType Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
11
Manual de Visual Basic Parte II 2012 2012
SqlDbType.Char, 10).Value = datos.SelectCommand.Parameters.Add("@ape",, SqlDbType.Char, datos.SelectCommand.Parameters.Add("@ape" TextBox1.Text datos.Fill(ds, "alumnitos") "alumnitos") 'ejecuta el data adapter, que abre la conexion conexion DGV.DataSource = ds.Tables("alumnitos" ds.Tables("alumnitos")) TextBox1.Text = "" "" TextBox1.Focus() End End If If End Sub End Sub End End Class
Mostrar alumnos o alumnas con radios button
Dim conex1 As New New Dim conex1 As SqlConnection("server=MIK3\io;database=Northwind1;trusted_connection=true" SqlConnection( "server=MIK3\io;database=Northwind1;trusted_connection=true")) If RadioButton1.Checked RadioButton1.Checked = True True Then Then If Dim Dim datos datos As As New New SqlDataAdapter SqlDataAdapter(("sexo" "sexo",, conex1) Dim Dim ds ds As As New Data. New Data.DataSet DataSet datos.SelectCommand.CommandType = CommandType CommandType.StoredProcedure .StoredProcedure '*** '*** "@sex",, SqlDbType.Char, SqlDbType.Char, 1).Value = 1 datos.SelectCommand.Parameters.Add("@sex" datos.SelectCommand.Parameters.Add( datos.Fill(ds, "Alumnos") "Alumnos") DGV.DataSource = ds.Tables("Alumnos" ds.Tables("Alumnos")) ElseIf RadioButton2.Checked RadioButton2.Checked = True True Then Then ElseIf Dim datos1 datos1 As As New New SqlDataAdapter( SqlDataAdapter("sexo" "sexo",, conex1) Dim Dim Dim ds1 ds1 As As New New Data. Data.DataSet DataSet CommandType.StoredProcedure .StoredProcedure '*** '*** datos1.SelectCommand.CommandType = CommandType datos1.SelectCommand.Parameters.Add("@sex" datos1.SelectCommand.Parameters.Add( "@sex",, SqlDbType SqlDbType.Char, .Char, 1).Value = 2 datos1.Fill(ds1, "Alumnos" "Alumnos")) DGV.DataSource = ds1.Tables("Alumnos" ds1.Tables("Alumnos")) End End If Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
12
Manual de Visual Basic Parte II 2012 2012
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
13
Manual de Visual Basic Parte II 2012 2012
En un sistema realizar el mantenimiento en consultas:
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
14
Manual de Visual Basic Parte II 2012 2012
UN TOOLsTRIP CON IMÁGENES
EN CONSULTA HACEMOS LOS SIGUIENTES FORMULARIO:
El menúStrip deberá estar acompañado de imágenes:
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
15
Manual de Visual Basic Parte II 2012 2012
Creamos un módulo (Globales) (Globales)
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
16
Manual de Visual Basic Parte II 2012 2012
Escribimos el siguiente Código: Module GLOBALES Module GLOBALES Public CONEX As New New Public CONEX As SqlConnection(("server=MIK3\io;database=Northwind1;trusted_connect System.Data.SqlClient.SqlConnection System.Data.SqlClient. ion=true")) ion=true" End Module End Module HACEMOS EL PROCEDIMIENTO ALMACENADO: create PROC create PROC consulta1 AS SELECT CATEGORYNAME CATEGORYNAME,, COUNT (*) (*) AS AS TOTAL FROM Categories FROM Categories AS AS C INNER INNER JOIN JOIN Products Products AS AS P ON C.CategoryID CategoryID==P.CategoryID ON GROUP BY GROUP BY CategoryName ORDER BY ORDER BY CategoryName EN VISUAL BASIC: Imports System.Data.SqlClient System.Data.SqlClient Imports Public Class CONSULTA1 CONSULTA1 Public Class Private Sub CONSULTA1_Load(sender CONSULTA1_Load(sender As As System. System.Object Object,, e As System. As System.EventArgs EventArgs)) Handles Handles Private Sub MyBase.Load MyBase.Load Dim datos datos As As New New SqlDataAdapter( SqlDataAdapter("consulta1" "consulta1",, CONEX) Dim Dim Dim DS DS As As New New Data. Data.DataSet DataSet datos.SelectCommand.CommandType = CommandType.StoredProcedure CommandType.StoredProcedure datos.Fill(DS, "QUERY1") "QUERY1") DGV.DataSource = DS.Tables("QUERY1" DS.Tables("QUERY1")) End Sub End Sub End End Class
CREATE PROC CREATE PROC CONSULTA2 @CATE INT @CATE AS SELECT ProductID, ProductID,ProductName ProductName,,UnitPrice UnitPrice,,UnitsInStock UnitsInStock,,COMPANYNAME COMPANYNAME,,CategoryID Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
17
Manual de Visual Basic Parte II 2012 2012
FROM Products AS AS P INNER INNER JOIN JOIN Suppliers Suppliers AS AS S ON ON P.SupplierID SupplierID==S.SupplierID FROM Products WHERE CategoryID= WHERE CategoryID=@CATE Imports System.Data.SqlClient Imports System.Data.SqlClient Public Class consulta02 consulta02 Public Class Private Sub ListBox1_SelectedIndexChanged( ListBox1_SelectedIndexChanged(ByVal ByVal sender sender As System. As System.Object Object,, ByVal ByVal e e As As Private Sub System.EventArgs System. EventArgs)) Handles Handles ListBox1.SelectedIndexChanged ListBox1.SelectedIndexChanged Dim datos datos As As New New SqlDataAdapter( SqlDataAdapter("query2" "query2",, conex) Dim datos.SelectCommand.CommandType = CommandType.StoredProcedure CommandType.StoredProcedure datos.SelectCommand.Parameters.Add("@cate" datos.SelectCommand.Parameters.Add( "@cate",, SqlDbType SqlDbType.Int).Value .Int).Value = ListBox1.SelectedValue Dim Dim ds ds As As New Data. New Data.DataSet DataSet datos.Fill(ds, "query2" "query2")) DGV2.DataSource = ds.Tables("query2" ds.Tables("query2")) End End Sub Sub Private Private Sub Sub consulta02_Load(sender consulta02_Load(sender As As System. System.Object Object,, e As As System. System.EventArgs EventArgs)) Handles Handles MyBase.Load MyBase.Load 'TODO: esta línea de código carga datos en la tabla 'NorthwindDataSet.Categories' Puede moverla o quitarla según sea necesario. necesario. Me Me.CategoriesTableAdapter.Fill( .CategoriesTableAdapter.Fill(Me Me.NorthwindDataSet.Categories) .NorthwindDataSet.Categories) End Sub Sub End End End Class
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
18
Manual de Visual Basic Parte II 2012 2012
AGREGAR UNA CONSULTA A UN LISTBOX
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
19
Manual de Visual Basic Parte II 2012 2012
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
20
Manual de Visual Basic Parte II 2012 2012
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
21
Manual de Visual Basic Parte II 2012 2012
Asignar los valores correspondientes al listbox
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
22
Manual de Visual Basic Parte II 2012 2012
Consultar entre dos precios. precios.
CREATE PROC CREATE PROC CONSULTA3 @ls float, @ls float, @li float @li AS SELECT ProductName ProductName,,UnitPrice UnitPrice,,Categoryname Categoryname,,COMPANYNAME FROM Products FROM Products AS AS P INNER INNER JOIN JOIN Suppliers Suppliers AS AS S ON ON P.SupplierID SupplierID==S.SupplierID SupplierID inner inner join join Categories Categories as as c on on P.CategoryID CategoryID==c.CategoryID WHERE UnitPrice WHERE UnitPrice between between @ls @ls and and @li Imports System.Data.SqlClient Imports System.Data.SqlClient Public Public Class Class consulta03 consulta03 Private Sub Button1_Click(sender Button1_Click(sender As As System. System.Object Object,, e As As System. System.EventArgs EventArgs)) Handles Handles Private Sub Button1.Click Dim datos As New New SqlDataAdapter( SqlDataAdapter("consulta3" "consulta3",, conex) Dim datos As datos.SelectCommand.CommandType = CommandType.StoredProcedure CommandType.StoredProcedure datos.SelectCommand.Parameters.Add("@ls" datos.SelectCommand.Parameters.Add( "@ls",, SqlDbType SqlDbType.Int).Value .Int).Value = TextBox1.Text datos.SelectCommand.Parameters.Add("@li" datos.SelectCommand.Parameters.Add( "@li",, SqlDbType.Int).Value SqlDbType.Int).Value = TextBox2.Text Dim ds ds As As New Data. New Data.DataSet DataSet Dim datos.Fill(ds, "query3" "query3")) Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
23
Manual de Visual Basic Parte II 2012 2012
DGV3.DataSource = ds.Tables("query3" ds.Tables("query3")) End Sub End Sub End Class End
Consultar productos q empiecen con una determinada letra. letra.
CREATE proc CREATE proc CONSULTAS4 @X NVARCHAR (40 @X 40)) AS SELECT ProductName ProductName,, UnitPrice UnitPrice,,CategoryID CategoryID,,SupplierID FROM Products FROM WHERE ProductName WHERE ProductName LIKE LIKE @X @X + '%' Imports System.Data.SqlClient Imports System.Data.SqlClient Public Public Class Class consulta04 consulta04 Private Sub TextBox1_KeyPress(sender TextBox1_KeyPress(sender As As Object, Object, e As As Private Sub System.Windows.Forms.KeyPressEventArgs System.Windows.Forms. KeyPressEventArgs)) Handles Handles TextBox1.KeyPress TextBox1.KeyPress Dim datos Dim datos As As New New SqlDataAdapter( SqlDataAdapter("consultas4" "consultas4",, conex) datos.SelectCommand.CommandType = CommandType CommandType.StoredProcedure .StoredProcedure Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
24
Manual de Visual Basic Parte II 2012 2012
"@x",, SqlDbType.VarChar).Value SqlDbType.VarChar).Value = TextBox1.Text datos.SelectCommand.Parameters.Add("@x" datos.SelectCommand.Parameters.Add( Dim ds ds As As New Data. New Data.DataSet DataSet Dim datos.Fill(ds, "query4" "query4")) DGV4.DataSource = ds.Tables("query4" ds.Tables("query4")) End End Sub Sub End End Class
Filtrar por el nombre del producto.
CREATE PROC CONSULTA5 CREATE PROC @N INT @N AS SELECT PRODUCTNAME PRODUCTNAME,, UNITPRICE, UNITPRICE ,UNITSINSTOCK UNITSINSTOCK,,SUPPLIERID FROM Products FROM WHERE SupplierID= WHERE SupplierID =@N Imports System.Data.SqlClient Imports System.Data.SqlClient Public Public Class Class consulta05 consulta05 Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
25
2012 Manual de Visual Basic Parte II 2012
Private Sub ListBox1_SelectedIndexChanged(sender ListBox1_SelectedIndexChanged(sender As As System. System.Object Object,, e As As Private Sub System.EventArgs System. EventArgs)) Handles Handles ListBox1.SelectedIndexChanged ListBox1.SelectedIndexChanged Dim Dim datos datos As As New New SqlDataAdapter( SqlDataAdapter("consulta5" "consulta5",, conex) datos.SelectCommand.CommandType = CommandType.StoredProcedure CommandType.StoredProcedure datos.SelectCommand.Parameters.Add("@n" datos.SelectCommand.Parameters.Add( "@n",, SqlDbType SqlDbType.Int).Value .Int).Value = ListBox1.SelectedValue Dim Dim ds ds As As New Data. New Data.DataSet DataSet "query5")) datos.Fill(ds, "query5" DGV5.DataSource = ds.Tables("query5" ds.Tables("query5")) End Sub Sub End Private Sub Sub consulta05_Load(sender consulta05_Load(sender As As System. System.Object Object,, e As As System. System.EventArgs EventArgs)) Handles Handles Private MyBase.Load MyBase.Load Me.SuppliersTableAdapter1.Fill( .SuppliersTableAdapter1.Fill(Me Me.Northwind1DataSet2.Suppliers) .Northwind1DataSet2.Suppliers) Me End End Sub Sub End Class End
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
26
2012 Manual de Visual Basic Parte II 2012
Filtrar por número de orden:
CREATE PROC CONSULTA6 CREATE PROC @N INT @N AS
SELECT O.OrderID OrderID,,P.PRODUCTID PRODUCTID,,P.PRODUCTNAME PRODUCTNAME,,P.UNITPRICE UNITPRICE,,OD OD..QUANTITY FROM [Order Details] FROM Details] AS AS OD OD INNER INNER JOIN JOIN ORDERS ORDERS AS AS O ON ON O.OrderID OrderID==OD OD..OrderID OrderID INNER INNER JOIN JOIN PRODUCTS PRODUCTS AS AS P ON P.ProductID ON ProductID==OD OD..ProductID WHERE O.OrderID=@N WHERE Imports System.Data.SqlClient Imports System.Data.SqlClient Public Public Class Class consulta06 consulta06 Private Sub Button1_Click(sender Button1_Click(sender As As System. System.Object Object,, e As As System. System.EventArgs EventArgs)) Handles Handles Private Sub Button1.Click Dim datos As New New SqlDataAdapter( SqlDataAdapter("consulta6" "consulta6",, conex) Dim datos As datos.SelectCommand.CommandType = CommandType.StoredProcedure CommandType.StoredProcedure "@n",, SqlDbType SqlDbType.Int).Value .Int).Value = TextBox1.Text datos.SelectCommand.Parameters.Add("@n" datos.SelectCommand.Parameters.Add(
Dim Dim ds ds As As New Data. New Data.DataSet DataSet datos.Fill(ds, "query6" "query6")) DGV6.DataSource = ds.Tables("query6" ds.Tables("query6")) End End Sub Sub End Class End
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
27
2012 Manual de Visual Basic Parte II 2012
Con radiobutton mostrar los productos con stock o sin s in stock.
CREATE PROC CREATE PROC CONSULTA7 AS SELECT PRODUCTiD PRODUCTiD,, PRODUCTNAME PRODUCTNAME,,UNITPRICE UNITPRICE,,UNITSINSTOCK FROM Products FROM WHERE UnitsInStock= WHERE UnitsInStock=0 CREATE PROC PROC CONSULTAS7 CREATE AS SELECT PRODUCTiD PRODUCTiD,, PRODUCTNAME PRODUCTNAME,,UNITPRICE UNITPRICE,,UNITSINSTOCK FROM Products FROM WHERE UnitsInStock!= WHERE UnitsInStock!=00 Imports Imports System.Data.SqlClient System.Data.SqlClient Public Public Class Class consulta07 consulta07 Private Sub Private Sub RadioButton1_CheckedChanged(sender RadioButton1_CheckedChanged(sender As As System. System.Object Object,, e As As Handles RadioButton1.CheckedChanged RadioButton1.CheckedChanged System.EventArgs)) Handles System.EventArgs Dim Dim datos datos As As New New SqlDataAdapter( SqlDataAdapter("consultas7" "consultas7",, conex) CommandType.StoredProcedure .StoredProcedure datos.SelectCommand.CommandType = CommandType Dim ds Dim ds As As New Data. New Data.DataSet DataSet datos.Fill(ds, "query7" "query7")) DGV7.DataSource = ds.Tables("query7" ds.Tables("query7")) End Sub End Sub Private Sub Sub RadioButton2_CheckedChanged(sender RadioButton2_CheckedChanged(sender As As System. System.Object Object,, e As As Private EventArgs)) Handles Handles RadioButton2.CheckedChanged RadioButton2.CheckedChanged System.EventArgs System. Dim Dim datos datos As As New New SqlDataAdapter( SqlDataAdapter("consulta7" "consulta7",, conex) datos.SelectCommand.CommandType = CommandType.StoredProcedure CommandType.StoredProcedure Dim ds Dim ds As As New Data. New Data.DataSet DataSet "query8")) datos.Fill(ds, "query8" DGV7.DataSource = ds.Tables("query8" ds.Tables("query8")) End Sub End Sub End Class End
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
28
2012 Manual de Visual Basic Parte II 2012
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
29
2012 Manual de Visual Basic Parte II 2012
Mostrar los productos discontinuados.
CREATE PROC CONSU8 CREATE PROC @N INT @N AS SELECT PRODUCTID PRODUCTID,, PRODUCTNAME PRODUCTNAME,,UNITPRICE UNITPRICE,,DISCONTINUED FROM Products FROM WHERE Discontinued= WHERE Discontinued=@N Imports System.Data.SqlClient Imports System.Data.SqlClient Public Class consulta08 consulta08 Public Class Private Sub Private Sub CheckBox1_CheckedChanged( CheckBox1_CheckedChanged(ByVal ByVal sender sender As As System. System.Object Object,, ByVal ByVal e e As As EventArgs)) Handles Handles CheckBox1.CheckedChanged CheckBox1.CheckedChanged System.EventArgs System. Dim Dim datos datos As As New New SqlDataAdapter( SqlDataAdapter("consu8" "consu8",, conex) datos.SelectCommand.CommandType = CommandType.StoredProcedure CommandType.StoredProcedure datos.SelectCommand.Parameters.Add("@n" datos.SelectCommand.Parameters.Add( "@n",, SqlDbType SqlDbType.Bit).Value .Bit).Value = CheckBox1.Checked Dim Dim ds ds As As New Data. New Data.DataSet DataSet "query9")) datos.Fill(ds, "query9" DGV8.DataSource = ds.Tables("query9" ds.Tables("query9")) End End Sub Sub End Class End
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
30
2012 Manual de Visual Basic Parte II 2012
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
31
2012 Manual de Visual Basic Parte II 2012
EJERCICIOS COMPLEMENTARIOS SOBRE CONSULTAS A BASE DE DATOS USANDO VISUAL BASIC 2010 Programación Aplicada I 1.
Modo Diseño:
Consultas en SQL: create proc TipBusComienza create proc @t nvarchar @t nvarchar((40 40)) as select ProductId, select ProductId, ProductName ProductName,, UnitPrice, UnitPrice, UnitsInStock UnitsInStock,, Categoryname Categoryname,, Companyname from Products from Products as as p inner inner join join Categories Categories as as c on on c.CategoryID CategoryID==p.CategoryID CategoryID inner inner join join Suppliers Suppliers as as s on on s.SupplierID SupplierID==p.SupplierID where ProductName where ProductName like like @t+ @t+ '%' Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
32
Manual de Visual Basic Parte II 2012 2012
create proc TipBusTermina create proc @t nvarchar @t nvarchar((40 40)) as select ProductId, select ProductId, ProductName ProductName,, UnitPrice, UnitPrice, UnitsInStock UnitsInStock,, Categoryname Categoryname,, Companyname from Products from Products as as p inner inner join join Categories Categories as as c on on c.CategoryID CategoryID==p.CategoryID CategoryID inner inner join join Suppliers Suppliers as as s on on s.SupplierID SupplierID= =p. SupplierID where ProductName where ProductName like like '%'+ '%'+@t @t create proc TipBusContiene create proc @t nvarchar @t nvarchar((40 40)) as select ProductId, select ProductId, ProductName ProductName,, UnitPrice, UnitPrice, UnitsInStock UnitsInStock,, Categoryname Categoryname,, Companyname from Products from Products as as p inner inner join join Categories Categories as as c on on c.CategoryID CategoryID==p.CategoryID CategoryID inner inner join join Suppliers as as s on on s.SupplierID SupplierID==p.SupplierID Suppliers where ProductName where ProductName like like '%'+ '%'+@t @t++'%' '%' create proc TipBusNoContiene create proc @t nvarchar @t nvarchar((40 40)) as select ProductId, select ProductId, ProductName ProductName,, UnitPrice, UnitPrice, UnitsInStock UnitsInStock,, Categoryname Categoryname,, Companyname from Products from Products as as p inner inner join join Categories Categories as as c on on c.CategoryID CategoryID==p.CategoryID CategoryID inner inner join join Suppliers as as s on on s.SupplierID SupplierID==p.SupplierID Suppliers where ProductName where ProductName not not like like '%' '%'++@t @t++'%' '%' create proc TipBusIgualA create proc @t nvarchar @t nvarchar((40 40)) as select ProductId, select ProductId, ProductName ProductName,, UnitPrice, UnitPrice, UnitsInStock UnitsInStock,, Categoryname Categoryname,, Companyname from Products from Products as as p inner inner join join Categories Categories as as c on on c.CategoryID CategoryID==p.CategoryID CategoryID inner inner join join Suppliers as as s on on s.SupplierID SupplierID==p.SupplierID Suppliers where ProductName where ProductName =@t
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
33
Manual de Visual Basic Parte II 2012 2012
Código:
Imports System.Data Imports System.Data.SqlClient .SqlClient Public Class Class Form1 Form1 Public Dim Dim var1, var1, var2, var3 As As String String Private Sub Sub TextBox1_KeyPress(sender As As Object Object, , e As As Private System.Windows.Forms.KeyPressEventArgs System.Windows.Forms. KeyPressEventArgs) ) Handles Handles TextBox1.KeyPress If If e.KeyChar e.KeyChar = Chr(13) Then Then Select Case Case (ListBox1.SelectedInd (ListBox1.SelectedIndex) ex) Select Case 0 Case 0 var1 = "TipBusComienza" "TipBusComienza" Case 1 1 Case var1 = "TipBusTermina" "TipBusTermina" Case 2 Case 2 var1 = "TipBusContiene" "TipBusContiene" Case Case 3 3 var1 = "TipBusNoContiene" Case 4 4 Case var1 = "TipBusIgualA" "TipBusIgualA" End Select Select End If If ListBox1.SelectedIndex Then Then TextBox1.Focus() End If If End TextBox1.Focus() Dim Dim conex conex As As New New SqlConnection( SqlConnection("server=.;database=Northwind;trusted_connection=true" ) Dim Dim datos datos As As New New SqlDataAdapter(var1, SqlDataAdapter (var1, conex) Dim ds ds As As New New Data. Data.DataSet DataSet Dim '*** datos.SelectCommand.CommandType = CommandType.StoredProcedure CommandType.StoredProcedure '*** datos.SelectCommand.Parameters.Add( "@t" "@t", , SqlDbType SqlDbType.NVarChar, .NVarChar, 40).Value = TextBox1.Text datos.Fill(ds, "Query1") "Query1" ) DGV.DataSource = ds.Tables("Query1" ds.Tables( "Query1") ) TextBox1.Text TextBox1.T ext = "" "" TextBox1.Focus() End If End If End End Sub Sub End Class End
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
34
Manual de Visual Basic Parte II 2012 2012
Pantallas:
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
35
Manual de Visual Basic Parte II 2012 2012
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
36
Manual de Visual Basic Parte II 2012 2012
Modo Diseño:
Consultas en SQL: create proc selec1 create proc as select ProductName, select ProductName, UnitPrice UnitPrice,, UnitsinStock UnitsinStock,, CategoryID, CategoryID, Discontinued from Products from where UnitsinStock!= where UnitsinStock!=00 create proc proc selec2 create as select ProductName, select ProductName, UnitPrice UnitPrice,, UnitsinStock UnitsinStock,, CategoryID, CategoryID, Discontinued from Products from where Discontinued= where Discontinued=0 create proc create proc selec3 @cat int @cat Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
37
Manual de Visual Basic Parte II 2012 2012
as select ProductName, select ProductName, UnitPrice UnitPrice,, UnitsinStock UnitsinStock,, CategoryID, CategoryID, Discontinued from Products from where CategoryID= where CategoryID=@cat create proc create proc selec4 as select ProductName, select ProductName, UnitPrice UnitPrice,, UnitsinStock UnitsinStock,, CategoryID, CategoryID, Discontinued from Products from
Código:
Imports Imports System.Data System.Data.SqlClient .SqlClient Public Public Class Class Form2 Form2 Dim var1, As String String Dim var1, var2 As Private Private Sub Sub Button1_Clic Button1_Click(sender k(sender As System. As System.Object Object, , e As System. As System.EventArgs EventArgs) ) Handles Handles Button1.Click Dim conex As New New SqlConnection( SqlConnection ("server=.;database=Northwind;trusted_connection=true" ) Dim conex As If RadioButton1.Checked True Then Then If RadioButton1.Checked = True var1 = "selec1" "selec1" Dim datos2 As New New SqlDataAdapter SqlDataAdapter(var1, (var1, conex) Dim datos2 As Dim ds2 ds2 As As New Data. New Data.DataSet DataSet Dim '*** datos2.SelectCommand.CommandType = CommandType.StoredProcedure CommandType.StoredProcedure '*** datos2.Fill(ds2, "Query1" "Query1") ) "Query1") ) DGV.DataSource DGV.DataSo urce = ds2.Tables( ds2.Tables("Query1" ElseIf RadioButton2.Checked = True ElseIf RadioButton2.Checked True Then Then var1 = "selec2" "selec2" Dim datos As New New SqlDataAdapter SqlDataAdapter( ("selec2", "selec2", conex) Dim datos As Dim ds As New New Data. Data.DataSet DataSet Dim ds As datos.SelectCommand.CommandType = CommandType CommandType.StoredProcedure .StoredProcedure '*** '*** datos.Fill(ds, "Query2") "Query2" ) "Query2") ) DGV.DataSource DGV.DataSo urce = ds.Tables( ds.Tables("Query2" ElseIf RadioButton3.Checked RadioButton3.Checked = True True Then Then ElseIf var1 = "selec3" "selec3" Dim datos1 As New New SqlDataAdapter SqlDataAdapter(var1, (var1, conex) Dim datos1 As Dim ds1 ds1 As As New Data. New Data.DataSet DataSet Dim datos1.SelectCommand.CommandType = CommandType.StoredProcedure CommandType.StoredProcedure '*** '*** "@cat", , SqlDbType SqlDbType.NVarChar, .NVarChar, 40).Value = datos1.SelectCommand.Parameters.Add( "@cat" TextBox1.Text datos1.Fill(ds1, "Query3") "Query3") DGV.DataSource DGV.DataSo urce = ds1.Tables( ds1.Tables("Query3" "Query3") ) ElseIf RadioButton4.Checked = True ElseIf RadioButton4.Checked True Then Then var1 = "selec4" "selec4" Dim datos As New New SqlDataAdapter SqlDataAdapter(var1, (var1, conex) Dim datos As Dim ds As New New Data. Data.DataSet DataSet Dim ds As CommandType.StoredProcedure .StoredProcedure '*** '*** datos.SelectCommand.Com datos.Sele ctCommand.CommandType mandType = CommandType datos.Fill(ds, "Query4") "Query4" ) "Query4") ) DGV.DataSource DGV.DataSo urce = ds.Tables( ds.Tables("Query4" End If If End End Sub Sub End End End Class
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
38
Manual de Visual Basic Parte II 2012 2012
Pantallas:
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
39
Manual de Visual Basic Parte II 2012 2012
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
40
Manual de Visual Basic Parte II 2012 2012
2. Modo Diseño:
Consultas en SQL: create proc selec1 create proc as select ProductName select ProductName,, UnitPrice UnitPrice,, UnitsinStock, UnitsinStock, CategoryID CategoryID,, Discontinued from Products from where UnitsinStock!= where UnitsinStock!=00 create proc create proc selec2 as select ProductName select ProductName,, UnitPrice UnitPrice,, UnitsinStock, UnitsinStock, CategoryID CategoryID,, Discontinued from Products from where Discontinued= where Discontinued=0 create create proc proc selec3 @cat int @cat as select select ProductName ProductName,, UnitPrice UnitPrice,, UnitsinStock, UnitsinStock, CategoryID CategoryID,, Discontinued from Products from Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
41
Manual de Visual Basic Parte II 2012 2012 where CategoryID=@cat where CategoryID= create proc create proc selec4 as select ProductName select ProductName,, UnitPrice UnitPrice,, UnitsinStock, UnitsinStock, CategoryID CategoryID,, Discontinued from Products from
Código: Imports System.Data.SqlClient Imports Public Class Public Class Form3 Form3 Dim Dim var1 var1 As As String String Private Sub Private Sub RadioButton1_CheckedChanged(sender As System. As System.Object Object, , e As As System. System.EventArgs EventArgs) ) Handles Handles RadioButton3.CheckedChanged, RadioButton2.CheckedChanged, RadioButton1.CheckedChanged, RadioButton4.CheckedChanged Dim conex As New New SqlConnection( SqlConnection ("server=.;database=Northwind;trusted_connection=true" ) Dim conex As If RadioButton1.Checked = True If RadioButton1.Checked True Then Then var1 = "selec1" "selec1" Dim Dim datos2 datos2 As As New New SqlDataAdapter(var1, SqlDataAdapter (var1, conex) Dim ds2 ds2 As As New Data. New Data.DataSet DataSet Dim datos2.SelectCommand.CommandType = CommandType.StoredProcedure CommandType .StoredProcedure '*** '*** datos2.Fill(ds2, "Query1") "Query1") ) DGV.DataSource = ds2.Tables("Query1" ds2.Tables("Query1") ElseIf RadioButton2.Checked = True ElseIf RadioButton2.Checked True Then Then "selec2" var1 = "selec2" Dim Dim datos datos As As New New SqlDataAdapter ("selec2" "selec2", , conex) Dim Dim ds ds As As New New Data. Data.DataSet DataSet datos.SelectCommand.CommandType = CommandType.StoredProcedure CommandType.StoredProcedure '*** '*** datos.Fill(ds, "Query2") "Query2") DGV.DataSource = ds.Tables("Query2" ds.Tables("Query2") ) ElseIf RadioButton3.Checked = True ElseIf RadioButton3.Checked True Then Then If If RadioButton3.Checked Then Then True TextBox1.Enabled = True Else Else TextBox1.Enabled = False False End If If End TextBox1.Focus() ElseIf ElseIf RadioButton4.Checked RadioButton4.Checked = True True Then Then var1 = "selec4" "selec4" Dim datos datos As As New New SqlDataAdapter (var1, conex) Dim Dim Dim ds ds As As New New Data. Data.DataSet DataSet '*** datos.SelectCommand.CommandType = CommandType.StoredProcedure CommandType.StoredProcedure '*** datos.Fill(ds, "Query4") "Query4") ) DGV.DataSource = ds.Tables("Query4" ds.Tables("Query4") End If End If End Sub End Sub Private Private Sub Sub TextBox1_KeyPress(sender As As Object Object, , e As As System.Windows.Forms. System.Windows.Forms.KeyPressEventArgs KeyPressEventArgs) ) Handles Handles TextBox1.KeyPress If e.KeyChar = Chr(13) Then If e.KeyChar Then TextBox1.Focus() Dim conex As New New SqlConnection( SqlConnection("server=.;database=Northwind;trusted_connection=true" ) Dim conex As Dim Dim datos datos As As New New SqlDataAdapter ("selec3" "selec3", , conex) Dim Dim ds ds As As New New Data. Data.DataSet DataSet datos.SelectCommand.CommandType = CommandType.StoredProcedure CommandType.StoredProcedure '*** '*** SqlDbType.NVarChar, 40).Value = TextBox1.Text datos.SelectCommand.Parameters.Add( "@cat", "@cat", SqlDbType.NVarChar, datos.Fill(ds, "Query3") "Query3") ) DGV.DataSource = ds.Tables("Query3" ds.Tables("Query3") "" TextBox1.Text TextBox1.T ext = "" TextBox1.Focus() End If End If End Sub End Sub End Class End
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
42
Manual de Visual Basic Parte II 2012 2012
Pantallas:
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
43
Manual de Visual Basic Parte II 2012 2012
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
44
Manual de Visual Basic Parte II 2012 2012
3. Modo Diseño:
Código: Imports Imports System.Data System.Data.SqlClient .SqlClient Public Class Class Form4 Form4 Public Private Sub Private Sub MonthCalendar1_DateChanged(sender As As System. System.Object Object, , e As As System.Windows.Forms. DateRangeEventArgs DateRangeEventArgs) ) Handles Handles MonthCalen MonthCalendar1.DateC dar1.DateChanged hanged TextBox1.Text TextBox1.Te xt = MonthCalendar1.Selecti MonthCalendar1.SelectionStart onStart Dim traerdatos As New New SqlDataAdapter( SqlDataAdapter ("ejercicio4", "ejercicio4" , conex2) Dim traerdatos As traerdatos.SelectCommand.CommandType = CommandType.StoredProcedure CommandType.StoredProcedure "@fecha", , SqlDbType SqlDbType.DateTime).Value .DateTime).Value = traerdatos.SelectCommand.Parameters.Add( "@fecha" MonthCalendar1.SelectionStart 'fill = es abre la conexion, ejecuta la consulta Dim Dim contenedordatos As As New New Data. Data.DataSet DataSet categoria") ) traerdatos.Fill(contenedordatos, "con categoria" categoria") ) DataGridView1.DataSource = contenedordatos.Tables("con contenedordatos.Tables( "con categoria" End End Sub Sub Private Sub Sub Form4_Load(sender As As System. System.Object Object, , e As System. As System.EventArgs EventArgs) ) Handles Handles MyBase MyBase.Load .Load Private TextBox1.Enabled = False False End Sub Sub End End End Class
Consulta SQL: create proc create proc ejercicio4 @fecha datetime @fecha as select o.OrderId select OrderId,, (OrderDate OrderDate),), ProductName ProductName,, p.UnitPrice UnitPrice , Quantity Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
45
Manual de Visual Basic Parte II 2012 2012
from Products as as p from Products inner join inner join [Order Details] Details] as as od od on on od. od.ProductID ProductID =p.ProductID ProductID inner join join Orders Orders as as o on on o.OrderID OrderID =od od..OrderID inner where @fecha where @fecha==OrderDate
Pantallas:
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
46
Manual de Visual Basic Parte II 2012 2012
EJERCICIOS 1. Categorías categoriId
categorYname
Descripción
create proc categorias create proc as select CategoryID select CategoryID,,CategoryName CategoryName,,Description from Categories from Productos productoid
productname
unitprice
categoriId
create proc proc productos create @cat int @cat as select ProductID select ProductID,,ProductName ProductName,,UnitPrice UnitPrice,,CategoryID from (Products Products)) where CategoryID where CategoryID==@cat Imports System.Data.SqlClient Imports System.Data.SqlClient Public Public Class Class consulta13 consulta13 Private Sub consulta13_Load(sender consulta13_Load(sender As As System. System.Object Object,, e As System. As System.EventArgs EventArgs)) Handles Handles Private Sub MyBase.Load .Load This line of code loads data into the 'Northwind1DataSet.Categories' table. You MyBase 'TODO: can move, or remove it, as needed. needed. Me Me.CategoriesTableAdapter1.Fill( .CategoriesTableAdapter1.Fill(Me Me.Northwind1DataSet.Categories) .Northwind1DataSet.Categories) End Sub End Sub Dim conex conex As As New New SqlConnection( SqlConnection("Data Source=MIK3\io;Initial Dim Catalog=Northwind1;Integrated Security=True") Security=True") Private Sub DGVCAB_CellEnter(sender DGVCAB_CellEnter(sender As As Object Object,, e As As Private Sub System.Windows.Forms.DataGridViewCellEventArgs System.Windows.Forms. DataGridViewCellEventArgs)) Handles DGVCAB.CellEnter Handles DGVCAB.CellEnter Dim Dim detalle detalle As As New New SqlDataAdapter( SqlDataAdapter("select ProductID ,ProductName ,UnitPrice ,CategoryID Products where CategoryID =@cate" , conex) =@cate", Dim Dim DB DB from As As New Data. New Data.DataSet DataSet Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
47
Manual de Visual Basic Parte II 2012 2012
SqlDbType.Int).Value .Int).Value = detalle.SelectCommand.Parameters.Add( "@cate",, SqlDbType detalle.SelectCommand.Parameters.Add("@cate" DGVCAB.Rows(e.RowIndex).Cells(0).Value detalle.Fill(DB, "detalle" "detalle")) DGVDET.DataSource = DB.Tables("detalle" DB.Tables("detalle")) End End Sub Sub End End Class
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
48
Manual de Visual Basic Parte II 2012 2012
1. ORDERS ORDERID
ORDERDATE
FREIGHT
create proc ord create proc as SELECT OrderID OrderID,, OrderDate, OrderDate,Freight FROM Orders FROM Orders ORDERDETAILS Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
49
Manual de Visual Basic Parte II 2012 2012
ORDERID
DISCOUNT
PRODUCTID
PRODUCTNAME UNITPRICE QUANTITI
create proc ordet create proc @n int @n as SELECT OrderID OrderID,,Discount Discount,,P.ProductID ProductID,,ProductnAME ProductnAME,,P.UnitPrice FROM [Order Details] FROM Details] OD OD INNER INNER JOIN JOIN Products Products P ON ON P.ProductID ProductID==OD OD..ProductID where OrderID where OrderID==@n @n
Imports System.Data.SqlClient System.Data.SqlClient Imports Public Class CONSULTA14 CONSULTA14 Public Class Private Sub CONSULTA14_Load( CONSULTA14_Load(ByVal ByVal sender sender As System. As System.Object Object,, ByVal ByVal e e As As Private Sub System.EventArgs System. EventArgs)) Handles Handles MyBase MyBase.Load .Load Dim datos datos As As New New SqlDataAdapter( SqlDataAdapter("ord" "ord",, conex) Dim datos.SelectCommand.CommandType = CommandType.StoredProcedure CommandType.StoredProcedure Dim ds As Dim ds As New Data. New Data.DataSet DataSet datos.Fill(ds, "consulta14" "consulta14")) DataGridView1.DataSource = ds.Tables("consulta14" ds.Tables("consulta14")) End Sub End Sub Private Private Sub Sub DataGridView1_CellEnter( DataGridView1_CellEnter(ByVal ByVal sender sender As As Object, Object, ByVal ByVal e e As As DataGridViewCellEventArgs)) Handles DataGridView1.CellEnter Handles DataGridView1.CellEnter System.Windows.Forms.DataGridViewCellEventArgs System.Windows.Forms. Dim Dim datos datos As As New New SqlDataAdapter( SqlDataAdapter("ordet" "ordet",, conex) datos.SelectCommand.CommandType = CommandType.StoredProcedure CommandType.StoredProcedure "@n",, SqlDbType SqlDbType.Int).Value .Int).Value = datos.SelectCommand.Parameters.Add("@n" datos.SelectCommand.Parameters.Add( DataGridView1.Rows(e.RowIndex).Cells(0).Value Dim Dim ds ds As As New Data. New Data.DataSet DataSet datos.Fill(ds, "consulta141" "consulta141")) DataGridView2.DataSource = ds.Tables("consulta141" ds.Tables( "consulta141")) End Sub End Sub End Class End
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
50
2012 Manual de Visual Basic Parte II 2012
2. EMPLEADOID ADRESS
FIRSTNAME CITY
LASTNAME COUNTRY
MOSTRAR LA FOTO DEL EMPLEADO SELECCIONADO Me.EmployeesTableAdapter.Fill( Me.Northwind1DataSet3.Employees) .Northwind1DataSet3.Employees) Me.EmployeesTableAdapter.Fill(Me
Imports System.Data.SqlClient Imports System.Data.SqlClient Public Public Class Class consulta15 consulta15 Dim n Dim n As As Integer Integer Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
51
2012 Manual de Visual Basic Parte II 2012
Dim conex As Dim conex As New New SqlConnection( SqlConnection("Data Source=MIK3\io;Initial Catalog=Northwind1;Integrated Security=True") Security=True") Private Private Sub Sub DataGridView1_CellContentClick( DataGridView1_CellContentClick(ByVal ByVal sender sender As As System. System.Object Object,, ByVal ByVal e e As As DataGridViewCellEventArgs)) Handles DataGridView1.CellContentClick Handles DataGridView1.CellContentClick System.Windows.Forms.DataGridViewCellEventArgs System.Windows.Forms. n = DataGridView1.Rows(e.RowIndex).Cells(0).Value Image.FromFile( .FromFile(CStr CStr(n) (n) + ".jpg") ".jpg") PictureBox1.Image = Image End Sub End Sub Private Private Sub Sub consulta15_Load( consulta15_Load(ByVal ByVal sender sender As As System. System.Object Object,, ByVal e ByVal e As As System.EventArgs System. EventArgs)) Handles Handles MyBase MyBase.Load .Load Me.EmployeesTableAdapter.Fill( .EmployeesTableAdapter.Fill(Me Me.Northwind1DataSet3.Employees) .Northwind1DataSet3.Employees) Me End Sub Sub End End End Class
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
52
2012 Manual de Visual Basic Parte II 2012
3. EMPLEADOS EMPLOYEEID
LASTNAME
FIRSTNAME
Me.EmployeesTableAdapter.Fill(Me Me.EmployeesTableAdapter.Fill( Me.Northwind1DataSet.Employees) .Northwind1DataSet.Employees) ÓRDENES REALIZADAS POR: OrderID
(Nombe completo del empleado)
OrderDate
EmployeeId
CREATE proc ordxemp CREATE proc @e int @e as select orderid select orderid,,orderdate orderdate,, employeeid from orders from where employeeid where employeeid==@e @e (OrderId)
Productos Comprados en la orden: OrderId ProductID Productname
UnitPrice
quantity
CREATE PROC CON3 CREATE PROC @O INT @O AS SELECT O.ORDERID ORDERID,, P.ProductID ProductID,, PRODUCTNAME PRODUCTNAME,, P.UNITPRICE UNITPRICE,,QUANTITY FROM PRODUCTS FROM PRODUCTS P INNER INNER JOIN JOIN [ORDER DETAILS] DETAILS] OD OD ON ON OD. OD.PRODUCTID PRODUCTID==P.ProductID ProductID INNER INNER JOIN JOIN ORDERS ORDERS O ON ON O.ORDERID ORDERID==OD OD..ORDERID WHERE O.ORDERID WHERE ORDERID==@O
Imports System.Data.SqlClient Imports System.Data.SqlClient Public Class Form3 Form3 Public Class Private Private Sub Sub Form3_Load( Form3_Load(ByVal ByVal sender sender As As System. System.Object Object,, ByVal ByVal e e As System. As System.EventArgs EventArgs)) Handles Handles MyBase.Load MyBase.Load Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
53
2012 Manual de Visual Basic Parte II 2012
Me Me.EmployeesTableAdapter.Fill( .EmployeesTableAdapter.Fill(Me Me.Northwind1DataSet.Employees) .Northwind1DataSet.Employees) End Sub Sub End Private Sub Sub DataGridView1_CellClick( DataGridView1_CellClick(ByVal ByVal sender sender As As Object, Object, ByVal ByVal e e As As Private System.Windows.Forms.DataGridViewCellEventArgs System.Windows.Forms. DataGridViewCellEventArgs)) Handles DataGridView1.CellClick Handles DataGridView1.CellClick Dim Dim datos datos As As New New SqlDataAdapter( SqlDataAdapter("ordxemp" "ordxemp",, conex) datos.SelectCommand.CommandType = CommandType.StoredProcedure CommandType.StoredProcedure "@e",, SqlDbType SqlDbType.Int).Value .Int).Value = datos.SelectCommand.Parameters.Add("@e" datos.SelectCommand.Parameters.Add( DataGridView1.Rows(e.RowIndex).Cells(0).Value Dim Dim ds ds As As New Data. New Data.DataSet DataSet "consulta141")) datos.Fill(ds, "consulta141" DataGridView2.DataSource = ds.Tables("consulta141" ds.Tables( "consulta141")) Label2.Text = DataGridView1.Rows(e.RowIndex).Cells(1).Value + " " + " + DataGridView1.Rows(e.RowIndex).Cells(2).Value End Sub End Sub Private Private Sub Sub DataGridView2_CellClick( DataGridView2_CellClick(ByVal ByVal sender sender As As Object Object,, ByVal ByVal e e As As Handles DataGridView2.CellClick System.Windows.Forms.DataGridViewCellEventArgs)) Handles DataGridView2.CellClick System.Windows.Forms.DataGridViewCellEventArgs Dim Dim datos datos As As New New SqlDataAdapter( SqlDataAdapter("CON3" "CON3",, conex) datos.SelectCommand.CommandType = CommandType.StoredProcedure CommandType.StoredProcedure "@O",, SqlDbType SqlDbType.Int).Value .Int).Value = datos.SelectCommand.Parameters.Add("@O" datos.SelectCommand.Parameters.Add( DataGridView2.Rows(e.RowIndex).Cells(0).Value Dim Dim ds ds As As New Data. New Data.DataSet DataSet datos.Fill(ds, "consulta141" "consulta141")) DataGridView3.DataSource = ds.Tables("consulta141" ds.Tables( "consulta141")) Label4.Text = DataGridView2.Rows(e.RowIndex).Cells(0).Value End Sub End Sub End End Class
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
54
2012 Manual de Visual Basic Parte II 2012
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
55
2012 Manual de Visual Basic Parte II 2012
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
56
2012 Manual de Visual Basic Parte II 2012
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
57
57
2012 Manual de Visual Basic Parte II 2012
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
58
2012 Manual de Visual Basic Parte II 2012
INSERTAR EN UNA TABLA DE UBA BASE DE DATOS DESDE VISUAL BASIC EN ESTA OPORTUNIDAD PRIMERO CREAREMOS UNA TABLA “ PERSONA” CON LOS SIGUIENTES CAMPOS:
CREAMOS EL PROCEDIMIENTO ALMACENADO QUE NOS PERMITIRÁ INSERTAR UNA NUEVA PERSONA CREATE PROC INSERTAR_PERSO CREATE PROC @ID CHAR (8), @ID @N VARCHAR @N VARCHAR((30 30),), @A VARCHAR @A VARCHAR((40 40),), @E VARCHAR( @E VARCHAR(50 50),), @G CHAR( @G CHAR(1), @EC CHAR( @EC CHAR(1), @FN DATETIME @FN AS INSERT INTO INTO PERSONAS VALUES (@ID @ID,,@N @N,,@A @A,,@E @E,,@G @G,,@EC @EC,,@FN @FN)) Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
59
2012 Manual de Visual Basic Parte II 2012
VERIFICAMOS EJECUTANDO EL PROCEDIMIENTO ALMACENADO INSERTAR_PERSO EXEC INSERTAR_PERSO EXEC INSERTAR_PERSO '47060664' '47060664',,'KAREN JOHANA', JOHANA','ESTRADA AGUILAR',,'
[email protected]' AGUILAR' '
[email protected]',,'F' 'F',,'S' 'S',,'22/10/1991' HACEMOS LA SIGUIENTE CONSULTA PARA VERIFICAR: SELECT * FROM PERSONAS FROM OBTENIENTO EL SIGUIENTE RESULTADO:
OBJETO MaskedTextBox CAMBIAR LA MASCARA
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
60
2012 Manual de Visual Basic Parte II 2012
INSERTAR UNA PERSONA: Imports System.Data.SqlClient Imports System.Data.SqlClient Public Public Class Class Form1 Form1 Sub limpiar_ingreso() Sub limpiar_ingreso() TextBox1.Text = "" "" TextBox2.Text = "" "" TextBox3.Text = "" "" TextBox4.Text = "" "" TextBox6.Text = "" "" MaskedTextBox1.Text = "" "" TextBox1.Focus() End Sub Sub End Sub Sub cargar_datos() cargar_datos() Dim datos datos As As New New SqlDataAdapter( SqlDataAdapter(" select * from Personas" Personas",, conex) Dim Dim Dim ds ds As As New Data. New Data.DataSet DataSet "Tabla")) datos.Fill(ds, "Tabla" DataGridView1.DataSource = ds.Tables("Tabla" ds.Tables("Tabla")) End Sub Sub End Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
61
2012 Manual de Visual Basic Parte II 2012
Private Sub Private Sub Button1_Click(sender Button1_Click(sender As As System. System.Object Object,, e As As System. System.EventArgs EventArgs)) Handles Handles Button1.Click Dim respuesta Dim respuesta As As Integer Integer Dim sexo sexo As As Char Char Dim Dim Dim insert_per insert_per As As New New SqlCommand SqlCommand(("insertar_perso", "insertar_perso", conex) If RadioButton1.Checked True Then Then If RadioButton1.Checked = True sexo = "F" "F" ElseIf RadioButton2.Checked RadioButton2.Checked = True True Then Then ElseIf sexo = "M" "M" End End If If CommandType.StoredProcedure .StoredProcedure insert_per.CommandType = CommandType insert_per.Parameters.Add("@id" insert_per.Parameters.Add( "@id",, SqlDbType.Char, SqlDbType.Char, 8).Value = TextBox1.Text "@n",, SqlDbType.VarChar, SqlDbType.VarChar, 30).Value = TextBox2.Text insert_per.Parameters.Add("@n" insert_per.Parameters.Add( insert_per.Parameters.Add("@a" insert_per.Parameters.Add( "@a",, SqlDbType SqlDbType.VarChar, .VarChar, 40).Value = TextBox3.Text insert_per.Parameters.Add("@e" insert_per.Parameters.Add( "@e",, SqlDbType SqlDbType.VarChar, .VarChar, 50).Value = TextBox4.Text "@g",, SqlDbType.Char, SqlDbType.Char, 1).Value = sexo insert_per.Parameters.Add("@g" insert_per.Parameters.Add( insert_per.Parameters.Add( "@ec",, SqlDbType insert_per.Parameters.Add("@ec" SqlDbType.Char, .Char, 1).Value = TextBox6.Text "@fn",, SqlDbType SqlDbType.DateTime).Value .DateTime).Value = insert_per.Parameters.Add("@fn" insert_per.Parameters.Add( CDate CDate(MaskedTextBox1.Text) (MaskedTextBox1.Text) conex.Open() respuesta = insert_per.ExecuteNonQuery conex.Close() If If respuesta respuesta = 1 Then Then MessageBox.Show("Se MessageBox.Show( "Se grabó el registro" registro")) limpiar_ingreso() cargar_datos() End If If End End Sub End Sub End End Class
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
62
2012 Manual de Visual Basic Parte II 2012
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
63
2012 Manual de Visual Basic Parte II 2012
Ahora creamos la tabla “libros”
LA TABLA EDITORIAL Y LA TABLA AUTOR
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
64
Manual de Visual Basic Parte II 2012 2012
LLENAMOS LAS TABLA EDITORIALES Y AUTORES CON ALGUNOS DATOS:
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
65
Manual de Visual Basic Parte II 2012 2012
CREAMOS UN PROCEDIMIENTO ALMACENADO QUE NOS PERMITA INSERTAR NUEVOS LIBROS: use use Northwind1 CREATE@t CREATE proc proc inserlibros inserlibros varchar varchar( (50 50),), @t @ide int @ide int,, @e varchar( @e varchar(50 50),), @a datetime, @a datetime, @ida int @ida as insert into insert into Libros (Titulo Titulo,,IDEditorial IDEditorial,,Edicion Edicion,,AÑO_PUBLICACION AÑO_PUBLICACION,,Autor Autor)) values((@t values @t,,@ide @ide,,@e @e,,@a @a,,@ida @ida))
Imports System.Data.SqlClient Imports System.Data.SqlClient Public Class Form2 Form2 Public Class Sub limpiar_ingreso() Sub limpiar_ingreso() TextBox1.Text = "" "" TextBox2.Text = "" "" MaskedTextBox1.Text = "" "" TextBox1.Focus() End End cargar_datos() Sub Sub Sub Sub cargar_datos() Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
66
Manual de Visual Basic Parte II 2012 2012
Dim datos datos As As New New SqlDataAdapter( SqlDataAdapter(" select * from Libros" Libros",, conex) Dim Dim ds As New Data. New Data.DataSet DataSet Dim ds As datos.Fill(ds, "Tabla" "Tabla")) DataGridView1.DataSource = ds.Tables("Tabla" ds.Tables("Tabla")) End Sub Sub End Private Private Sub Sub Form2_Load( Form2_Load(ByVal ByVal sender sender As As System. System.Object Object,, ByVal ByVal e e As System. As System.EventArgs EventArgs)) Handles MyBase.Load Handles MyBase.Load Me Me.AUTORESTableAdapter.Fill( .AUTORESTableAdapter.Fill(Me Me.Northwind1DataSet1.AUTORES) .Northwind1DataSet1.AUTORES) Me Me.EDITORIALESTableAdapter1.Fill( .EDITORIALESTableAdapter1.Fill(Me Me.Northwind1DataSet.EDITORIALES) .Northwind1DataSet.EDITORIALES) End Sub End Sub Private Sub Sub Button1_Click( Button1_Click(ByVal ByVal sender sender As System. As System.Object Object,, ByVal ByVal e e As As System. System.EventArgs EventArgs)) Private Handles Button1.Click Handles Button1.Click Dim respuesta Dim respuesta As As Integer Integer Dim insert_per insert_per As As New New SqlCommand SqlCommand(("inserlibros", "inserlibros", conex) Dim insert_per.CommandType = CommandType CommandType.StoredProcedure .StoredProcedure insert_per.Parameters.Add("@t" insert_per.Parameters.Add( "@t",, SqlDbType SqlDbType.VarChar, .VarChar, 50).Value = TextBox1.Text SqlDbType.Int).Value = ListBox1.SelectedValue insert_per.Parameters.Add( "@ide",, SqlDbType.Int).Value insert_per.Parameters.Add("@ide" insert_per.Parameters.Add("@e" insert_per.Parameters.Add( "@e",, SqlDbType SqlDbType.VarChar, .VarChar, 50).Value = TextBox2.Text "@a",, SqlDbType SqlDbType.DateTime).Value .DateTime).Value = MaskedTextBox1.Text insert_per.Parameters.Add("@a" insert_per.Parameters.Add( insert_per.Parameters.Add("@ida" insert_per.Parameters.Add( "@ida",, SqlDbType SqlDbType.Int).Value .Int).Value = ListBox2.SelectedValue conex.Open() respuesta = insert_per.ExecuteNonQuery conex.Close() If respuesta respuesta = 1 Then Then If MessageBox.Show( MessageBox.Show("Se "Se grabó el registro" registro")) limpiar_ingreso() cargar_datos() End If If End End Sub End Sub End Class End
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
67
Manual de Visual Basic Parte II 2012 2012
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
68
Manual de Visual Basic Parte II 2012 2012
CONSULTAR, AGREGAR Y ELIMINAR REGISTROS EN LA TABLA CATEGORÍAS Creamos un origen de datos, escogiendo los campos Category ID, Category Name, Description de la tabla Categories:
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
69
Manual de Visual Basic Parte II 2012 2012
Arrastramos este hacia el formulario teniendo lo siguiente:
Código generado automáticamente: Public Class Form1 Form1 Public Class Private Sub Private Sub CategoriesBindingNavigatorSaveItem_Click( CategoriesBindingNavigatorSaveItem_Click(ByVal ByVal sender sender As As System. System.Object Object,, ByVal ByVal e e As System. As System.EventArgs EventArgs)) Handles Handles CategoriesBindingNavigatorSaveItem.Click CategoriesBindingNavigatorSaveItem.Click Me.Validate() .Validate() Me Me.CategoriesBindingSource.EndEdit() Me.CategoriesBindingSource.EndEdit() Me.TableAdapterManager.UpdateAll( Me.Northwind1DataSet) .Northwind1DataSet) Me.TableAdapterManager.UpdateAll(Me End Sub Sub End Private Sub Sub Form1_Load( Form1_Load(ByVal ByVal sender sender As As System. System.Object Object,, ByVal ByVal e e As As System. System.EventArgs EventArgs)) Private Handles Handles MyBase.Load MyBase.Load 'TODO: This line of code loads data into the 'Northwind1DataSet.Categories' table. You can move, or remove it, as needed. needed. Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
70
Manual de Visual Basic Parte II 2012 2012
Me.CategoriesTableAdapter.Fill( Me.Northwind1DataSet.Categories) .Northwind1DataSet.Categories) Me.CategoriesTableAdapter.Fill(Me End Sub Sub End End End Class Class Observando las categorías:
Agregando un nuevo registro:
El código se autogenera, sólo llenamos el nombre y la descripción:
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
71
Manual de Visual Basic Parte II 2012 2012
Damos en guardar:
Verificamos en sql:
También lo podríamos eliminar:
Guardamos:
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
72
Manual de Visual Basic Parte II 2012 2012
Verificamos en sql:
Con el ejercicio anterior también podemos observar los productos que pertenecen a esa categoría cargando la información en un DataGridView: Imports System.Data.SqlClient Imports System.Data.SqlClient Public Public Class Class Form1 Form1 Sub CargarDatos() Sub CargarDatos() Dim Dim conex conex As As New New SqlConnection(("server=MIK3\io;database=northwind1;trusted_connection=true" "server=MIK3\io;database=northwind1;trusted_connection=true")) SqlConnection Dim datos datos As As New New SqlDataAdapter( SqlDataAdapter("select Dim productname,unitprice,unitsinstock,categoryid from products where categoryid=@cate", categoryid=@cate" , conex) Dim Dim ds ds As As New Data. New Data.DataSet DataSet "@cate",, SqlDbType SqlDbType.Int).Value .Int).Value = datos.SelectCommand.Parameters.Add("@cate" datos.SelectCommand.Parameters.Add( CInt CInt(CategoryIDTextBox.Text) (CategoryIDTextBox.Text) datos.Fill(ds, "Detalle" "Detalle")) DataGridView1.DataSource = ds.Tables("Detalle" ds.Tables("Detalle")) End End Sub Sub Private Private Sub Sub CategoriesBindingNavigatorSaveItem_Click( CategoriesBindingNavigatorSaveItem_Click(ByVal ByVal sender sender As As System. System.Object Object,, ByVal ByVal e e As System. As System.EventArgs EventArgs)) Me Me.Validate() .Validate() Me.CategoriesBindingSource.EndEdit() Me.CategoriesBindingSource.EndEdit() Me.TableAdapterManager.UpdateAll(Me Me.TableAdapterManager.UpdateAll( Me.Northwind1DataSet) .Northwind1DataSet) End Sub Sub End Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
73
Manual de Visual Basic Parte II 2012 2012
Private Sub Form1_Load( Form1_Load(ByVal ByVal sender sender As As System. System.Object Object,, ByVal ByVal e e As As System. System.EventArgs EventArgs)) Private Sub Handles Handles MyBase.Load MyBase.Load 'TODO: This line of code loads data into the 'Northwind1DataSet.Categories' table. You can move, or remove it, as needed. needed. Me Me.CategoriesTableAdapter.Fill( .CategoriesTableAdapter.Fill(Me Me.Northwind1DataSet.Categories) .Northwind1DataSet.Categories) CargarDatos() End End Sub Sub Private Sub Sub CategoryIDTextBox_TextChanged( CategoryIDTextBox_TextChanged(ByVal ByVal sender sender As As System. System.Object Object,, ByVal e ByVal e As As Private System.EventArgs System. EventArgs)) Handles Handles CategoryIDTextBox.TextChanged CategoryIDTextBox.TextChanged CargarDatos() End Sub Sub End End End Class Class
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
BUSCAR LA INFORMACIÓN DE UN PRODUCTO DE UN DETERMINADO PRODUCTID: Imports System.Data.SqlClient Imports System.Data.SqlClient Public Class Public Class Form2 Form2 Private Sub Button1_Click( Button1_Click(ByVal ByVal sender sender As System. As System.Object Object,, ByVal ByVal e e As As System. System.EventArgs EventArgs)) Private Sub Handles Button1.Click Handles Button1.Click Dim conex conex As As New New Dim SqlConnection(("server=MIK3\io;database=northwind1;trusted_connection=true" SqlConnection "server=MIK3\io;database=northwind1;trusted_connection=true")) Dim Dim comando comando As As New New SqlCommand SqlCommand(("select productname, unitprice, unitsinstock, categoryid from products where productid= @id", @id" , conex) comando.Parameters.Add("@id" comando.Parameters.Add( "@id",, SqlDbType.Int).Value SqlDbType.Int).Value = CInt CInt(TextBox1.Text) (TextBox1.Text) Dim Dim registro registro As As SqlDataReader SqlDataReader conex.Open()
74
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
registro = comando.ExecuteReader() ' se utiliza utiliza cuando es una consulta el executereader trae una variable y la alamcena en registro registro registro.Read() If registro.HasRows True Then Then If registro.HasRows = True TextBox3.Text = registro.Item(0) TextBox5.Text = registro.Item(3) TextBox4.Text = registro.Item(1) TextBox2.Text = registro.Item(2) Else Else MessageBox.Show("NO MessageBox.Show( "NO HAY REGISTROS QUE MOSTRAR" MOSTRAR")) End If If End registro.Close() conex.Close() End End Sub Sub End Class End
75
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
Guardar en una lista los datos del producto de un determinado proveedor:
Imports System.Data.SqlClient Imports System.Data.SqlClient Public Public Class Class Form3 Form3 Private Sub Button1_Click( Button1_Click(ByVal ByVal sender sender As System. As System.Object Object,, ByVal ByVal e e As As System. System.EventArgs EventArgs)) Private Sub Handles Button1.Click Handles Button1.Click Dim conex conex As As New New Dim SqlConnection SqlConnection(("server=MIK3\io;database=northwind1;trusted_connection=true" "server=MIK3\io;database=northwind1;trusted_connection=true")) Dim Dim comando comando As As New New SqlCommand SqlCommand(("select productname, unitprice, unitsinstock, SupplierID from products where SupplierID= @id", @id" , conex) comando.Parameters.Add("@id" comando.Parameters.Add( "@id",, SqlDbType.Int).Value SqlDbType.Int).Value = CInt CInt(TextBox1.Text) (TextBox1.Text)
76
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
Dim registro As SqlDataReader SqlDataReader Dim registro As conex.Open() registro = comando.ExecuteReader() registro.Read() Do While registro.Read() Do While registro.Read() ListBox1.Items.Add(CStr ListBox1.Items.Add( CStr(registro.Item(0)) (registro.Item(0)) + "-" + "-" + CStr CStr(registro.Item(1)) (registro.Item(1)) + "-" + "-" + CStr(registro.Item(2)) + "-" CStr(registro.Item(2)) "-" + + CStr CStr(registro.Item(3))) (registro.Item(3))) Loop Loop registro.Close() conex.Close() End Sub End Sub End End Class
77
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
CREAR IN INICIO DE SESIÓN PARA EL SISTEMA Agregamos un nuevo elemento y escogemos Login Form:
78
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
Ahora crearemos una tabla de usuarios en SQL respectivo:
LLENAMOS CON ALGUNOS DATOS:
EN VISUAL BASIC: Imports System.Data.SqlClient Imports System.Data.SqlClient Public Class LoginForm1 LoginForm1 Public Class Private Sub Private Sub OK_Click( OK_Click(ByVal ByVal sender sender As As System. System.Object Object,, ByVal e ByVal e As System. As System.EventArgs EventArgs)) Handles Handles OK.Click Dim Dim VALOR VALOR As As Integer Integer
79
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
Dim conex As New New Dim conex As SqlConnection(("server=MIK3\io;database=northwind1;trusted_connection=true" "server=MIK3\io;database=northwind1;trusted_connection=true")) SqlConnection Dim Dim QUERY QUERY As As New New SqlCommand( SqlCommand("SELECT COUNT(*) FROM USUARIOS WHERE USUARIO=@U AND CONTRASEÑA=@P", CONTRASEÑA=@P", conex) "@U",, SqlDbType.VarChar, SqlDbType.VarChar, 20).Value = UsernameTextBox.Text QUERY.Parameters.Add("@U" QUERY.Parameters.Add( QUERY.Parameters.Add("@P" QUERY.Parameters.Add( "@P",, SqlDbType.VarChar, SqlDbType.VarChar, 20).Value = PasswordTextBox.Text conex.Open() VALOR = QUERY.ExecuteScalar() conex.Close() If If VALOR VALOR = 1 Then Then Form1.Show() .Show() Form1 Me.Hide() Me.Hide() Me.Close() Me.Close() Else Else MessageBox.Show( MessageBox.Show("USUARIO "USUARIO Y/O CONTRASEÑA INCORRECTA!!!" INCORRECTA!!!")) MessageBox MessageBox.Show( .Show("VUELVA "VUELVA A INGRESAR LO CORRECTO" CORRECTO")) UsernameTextBox.Text = Space(0) PasswordTextBox.Text = Space(0) UsernameTextBox.Focus() Me.Show() Me.Show() End End If If End Sub End Sub Private Sub Sub Cancel_Click( Cancel_Click(ByVal ByVal sender sender As As System. System.Object Object,, ByVal ByVal e e As System. As System.EventArgs EventArgs)) Private Handles Cancel.Click Handles Cancel.Click Me Me.Close() .Close() End Sub End Sub End Class Class End
80
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
SÍ SE EJECUTA!!!! CUANDO LA CONTRASEÑA O USUARIO ES INCORRECTO:
Cambiar contraseña desde otro formulario Agregamos un link en el LoginForm1:
AL HACER CLIC EN EL LINK NOS LLEVA A OTRO FORMULARIO: Private Sub LinkLabel1_LinkClicked( LinkLabel1_LinkClicked(ByVal ByVal sender sender As As System. System.Object Object,, ByVal ByVal e e As As Private Sub System.Windows.Forms.LinkLabelLinkClickedEventArgs System.Windows.Forms. LinkLabelLinkClickedEventArgs)) Handles Handles LinkLabel1.LinkClicked LinkLabel1.LinkClicked Form4 Form4.Show() .Show() End End Sub
81
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
EN EL FORMULARIO 4:
Imports System.Data.SqlClient Imports System.Data.SqlClient Public Public Class Class Form4 Form4 Private Sub Sub Button1_Click( Button1_Click(ByVal ByVal sender sender As System. As System.Object Object,, ByVal ByVal e e As As System. System.EventArgs EventArgs)) Private Handles Button1.Click Handles Button1.Click Dim conex conex As As New New Dim SqlConnection(("server=MIK3\io;database=northwind1;trusted_connection=true" SqlConnection "server=MIK3\io;database=northwind1;trusted_connection=true")) Dim Dim DATOS DATOS As As New New SqlCommand SqlCommand(("UPDATE USUARIOS SET CONTRASEÑA=@NP WHERE USUARIO=@U AND CONTRASEÑA=@P", CONTRASEÑA=@P", conex) If TextBox3.Text If TextBox3.Text = TextBox4.Text Then Then conex.Open() DATOS.Parameters.Add("@NP" DATOS.Parameters.Add( "@NP",, SqlDbType SqlDbType.VarChar, .VarChar, 20).Value = TextBox3.Text DATOS.Parameters.Add("@U" DATOS.Parameters.Add( "@U",, SqlDbType.VarChar, SqlDbType.VarChar, 20).Value = TextBox1.Text "@P",EXITOSO" , SqlDbType.VarChar, SqlDbType) .VarChar, 20).Value = TextBox2.Text DATOS.Parameters.Add("@P" DATOS.Parameters.Add( MessageBox.Show( .Show("CAMBIO "CAMBIO EXITOSO") MessageBox DATOS.ExecuteNonQuery() conex.Close() Else : MessageBox.Show( .Show("NO "NO SE HA CAMBIADO" CAMBIADO")) Else : MessageBox End End If If End Sub End Sub Private Sub Sub Button2_Click( Button2_Click(ByVal ByVal sender sender As System. As System.Object Object,, ByVal ByVal e e As System. As System.EventArgs EventArgs)) Private Handles Button2.Click Button2.Click Handles Me.Close() Me .Close() End Sub Sub End End End Class
82
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
83
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
CREANDO EL SISTEMA DE ASISTENCIA DE LOS ALUMNOS DE INGENIERÍA DE SISTEMAS A LA XII SEMANA SISTÉMICA CREAMOS LA BASE DE DATOS SEM_SIST
84
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
Buscar un alumno o por su código o por su apellido: create proc create proc buscar_parti @id varchar @id varchar((10 10)) as select * select from PARTICIPANTES from where IDPARTICIPANTE where IDPARTICIPANTE like like @id @id++'%'
85
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
create proc proc cod cod create @ap varchar((20 20)) @ap varchar as select * select from PARTICIPANTES from where APEPAT like where like @ap+ @ap+'%'
Imports System.Data.SqlClient Imports System.Data.SqlClient Public Class Form1 Form1 Public Class Private Sub TextBox1_KeyPress( TextBox1_KeyPress(ByVal ByVal sender sender As As Object Object,, ByVal e ByVal e As As Private Sub System.Windows.Forms.KeyPressEventArgs System.Windows.Forms. KeyPressEventArgs)) Handles Handles TextBox1.KeyPress TextBox1.KeyPress If RadioButton1.Checked = True If RadioButton1.Checked True Then Then Dim Dim datos datos As As New New SqlDataAdapter SqlDataAdapter(("buscar_parti" "buscar_parti",, CONEX) Dim Dim ds ds As As New Data. New Data.DataSet DataSet
86
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
CommandType.StoredProcedure .StoredProcedure datos.SelectCommand.CommandType = CommandType datos.SelectCommand.Parameters.Add("@id" datos.SelectCommand.Parameters.Add( "@id",, SqlDbType SqlDbType.VarChar, .VarChar, 10).Value = TextBox1.Text datos.Fill(ds, "participantes") "participantes") DataGridView1.DataSource = ds.Tables("participantes" ds.Tables( "participantes")) ElseIf ElseIf RadioButton2.Checked RadioButton2.Checked = True True Then Then Dim Dim datos1 datos1 As As New New SqlDataAdapter( SqlDataAdapter("cod" "cod",, CONEX) Dim ds1 ds1 As As New New Data. Data.DataSet DataSet Dim datos1.SelectCommand.CommandType = CommandType CommandType.StoredProcedure .StoredProcedure datos1.SelectCommand.Parameters.Add("@AP" datos1.SelectCommand.Parameters.Add( "@AP",, SqlDbType SqlDbType.VarChar, .VarChar, 20).Value = TextBox1.Text "participantes2")) datos1.Fill(ds1, "participantes2" DataGridView1.DataSource = ds1.Tables("participantes2" ds1.Tables("participantes2")) End If End If End Sub End Sub End Class End
87
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
88
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
MANTENIMIENTO DE INSTITUCIONES
89
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
MANTENIMIENTO DE CONFERENCIAS
90
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
NUEVO PARICIPANTE
Imports System.Data.SqlClient Imports System.Data.SqlClient Public Public Class Class Form4 Form4 Private Sub Form4_Load( Form4_Load(ByVal ByVal sender sender As As System. System.Object Object,, ByVal ByVal e e As System. As System.EventArgs EventArgs)) Private Sub Handles Handles MyBase.Load MyBase.Load 'TODO: This line of code loads data into the 'SEM_SISTDataSet3.INSTITUCIONES' table. You can move, or remove it, as needed. needed. Me.INSTITUCIONESTableAdapter.Fill( Me .INSTITUCIONESTableAdapter.Fill(Me Me.SEM_SISTDataSet3.INSTITUCIONES) .SEM_SISTDataSet3.INSTITUCIONES) End Sub Sub End Sub Sub limpiar_ingreso() limpiar_ingreso() TextBox1.Text = "" "" "" TextBox2.Text = "" TextBox3.Text = "" "" "" ComboBox1.Text = "" "" TextBox4.Text = "" TextBox5.Text = "" "" TextBox1.Focus() End Sub End Sub Sub cargar_datos() cargar_datos() Sub Dim Dim datos datos As As New New SqlDataAdapter( SqlDataAdapter(" select * from PARTICIPANTES" PARTICIPANTES",, CONEX) Dim ds ds As As New Data. New Data.DataSet DataSet Dim datos.Fill(ds, "Tabla" "Tabla"))
91
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
DataGridView1.DataSource = ds.Tables("Tabla" ds.Tables("Tabla")) End Sub Sub End Private Private Sub Sub Button1_Click( Button1_Click(ByVal ByVal sender sender As System. As System.Object Object,, ByVal ByVal e e As As System. System.EventArgs EventArgs)) Handles Button1.Click Handles Button1.Click Dim respuesta respuesta As As Integer Integer Dim Dim Dim sexo sexo As As Char Char Dim Dim insert_par insert_par As As New New SqlCommand SqlCommand(("InsertaParticipante" "InsertaParticipante",, CONEX) If RadioButton1.Checked If RadioButton1.Checked = True True Then Then sexo = "1" "1" ElseIf ElseIf RadioButton2.Checked RadioButton2.Checked = True True Then Then "2" sexo = "2" End End If If insert_par.CommandType = CommandType CommandType.StoredProcedure .StoredProcedure "@id",, SqlDbType SqlDbType.Char, .Char, 10).Value = TextBox1.Text insert_par.Parameters.Add("@id" insert_par.Parameters.Add( insert_par.Parameters.Add("@ap" insert_par.Parameters.Add( "@ap",, SqlDbType.VarChar, SqlDbType.VarChar, 20).Value = TextBox2.Text insert_par.Parameters.Add("@am" insert_par.Parameters.Add( "@am",, SqlDbType SqlDbType.VarChar, .VarChar, 40).Value = TextBox3.Text insert_par.Parameters.Add("@n" insert_par.Parameters.Add( "@n",, SqlDbType.VarChar, SqlDbType.VarChar, 50).Value = TextBox4.Text "@s",, SqlDbType.Char, SqlDbType.Char, 1).Value = sexo insert_par.Parameters.Add("@s" insert_par.Parameters.Add( "@e",, SqlDbType SqlDbType.VarChar, .VarChar, 45).Value = TextBox5.Text insert_par.Parameters.Add("@e" insert_par.Parameters.Add( insert_par.Parameters.Add("@i" insert_par.Parameters.Add( "@i",, SqlDbType SqlDbType.Int).Value .Int).Value = ComboBox1.SelectedValue CONEX.Open() respuesta = insert_par.ExecuteNonQuery CONEX.Close() If respuesta respuesta = 1 Then Then If MessageBox.Show( MessageBox.Show("Se "Se grabó el registro" registro")) limpiar_ingreso() cargar_datos() End If If End End Sub End Sub End Class End
92
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
REPORTING SERVICE AGREGAMOS UN NUEVO ELEMENTO (UN REPORTE):
ACEPTAMOS Y CREAMOS UN REPORTE:
93
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
EN EL FORMULARIO ESCOGEMOS EL OBJETO REPORTVIEWER
94
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
EJECUTAMOS
REPORTE DE VENTA DE TRUCHAS:
95
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
96
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
Ventas por los empleados de cada año:
Órdenes por empleados en los meses:
97
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
Productos:
98
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
Public Class Public Class Form5 Form5 Private Sub Form5_Load(sender Form5_Load(sender As System. As System.Object Object,, e As System. As System.EventArgs EventArgs)) Handles Handles Private Sub MyBase.Load MyBase.Load Me Me.CategoriesTableAdapter.Fill( .CategoriesTableAdapter.Fill(Me Me.NorthwindDataSet6.Categories) .NorthwindDataSet6.Categories) ComboBox1.Text = Space(0) End Sub Sub End Private Private Sub Sub ComboBox1_SelectedIndexChanged(sender ComboBox1_SelectedIndexChanged(sender As As System. System.Object Object,, e As As System.EventArgs System. EventArgs)) Handles Handles ComboBox1.SelectedIndexChanged ComboBox1.SelectedIndexChanged Me Me.CATEGORIASTableAdapter.Fill( .CATEGORIASTableAdapter.Fill(Me Me.NorthwindDataSet5.CATEGORIAS) .NorthwindDataSet5.CATEGORIAS)
99
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
Me.REPORTESTableAdapter.Fill(Me Me.REPORTESTableAdapter.Fill( Me.NorthwindDataSet4.REPORTES, .NorthwindDataSet4.REPORTES, ComboBox1.SelectedValue) Me Me.ReportViewer1.RefreshReport() .ReportViewer1.RefreshReport() End End Sub Sub End Class End
Libros con páginas
100
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
Clientes
Public Public Class Class Form7 Form7 Private Sub Form7_Load(sender Form7_Load(sender As System. As System.Object Object,, e As System. As System.EventArgs EventArgs)) Handles Handles Private Sub MyBase.Load MyBase.Load 'TODO: esta línea de código carga datos en la tabla 'NorthwindDataSet8.Suppliers' Puede moverla o quitarla según sea necesario. necesario. Me.SuppliersTableAdapter.Fill( .SuppliersTableAdapter.Fill(Me Me.NorthwindDataSet8.Suppliers) .NorthwindDataSet8.Suppliers) Me 'TODO: esta línea de código carga datos en la tabla 'NorthwindDataSet7.Customers' Puede moverla o quitarla según sea necesario. necesario. Me Me.CustomersTableAdapter.Fill( .CustomersTableAdapter.Fill(Me Me.NorthwindDataSet7.Customers) .NorthwindDataSet7.Customers) Me.ReportViewer1.RefreshReport() .ReportViewer1.RefreshReport() Me Me.ReportViewer2.RefreshReport() Me.ReportViewer2.RefreshReport() End End Sub Sub End End Class
101
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
102
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
Ver empleado y Órdenes que ha realizado
Reporte:
103
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
Imports System.Data.SqlClient Imports System.Data.SqlClient Public Class Public Class Form1 Form1 Private Sub Private Sub EmployeesBindingNavigatorSaveItem_Click(sender EmployeesBindingNavigatorSaveItem_Click(sender As As System. System.Object Object,, e As As Handles EmployeesBindingNavigatorSaveItem.Click EmployeesBindingNavigatorSaveItem.Click System.EventArgs)) Handles System.EventArgs Me Me.Validate() .Validate() Me.EmployeesBindingSource.EndEdit() Me.EmployeesBindingSource.EndEdit() Me.TableAdapterManager.UpdateAll( Me.TableAdapterManager.UpdateAll(Me Me.NorthwindDataSet) .NorthwindDataSet) End End Sub Sub Private Sub Sub Form1_Load(sender Form1_Load(sender As As System. System.Object Object,, e As As System. System.EventArgs EventArgs)) Handles Handles Private MyBase.Load MyBase.Load Me Me.EmployeesTableAdapter.Fill( .EmployeesTableAdapter.Fill(Me Me.NorthwindDataSet.Employees) .NorthwindDataSet.Employees) End Sub End Sub
104
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
Private Sub Private Sub EmployeeIDTextBox_TextChanged(sender EmployeeIDTextBox_TextChanged(sender As As System. System.Object Object,, e As As EventArgs)) Handles Handles EmployeeIDTextBox.TextChanged EmployeeIDTextBox.TextChanged System.EventArgs System. Dim Dim conex conex As As New New SqlConnection(("server=.;database=Northwind;trusted_connection=true" "server=.;database=Northwind;trusted_connection=true")) SqlConnection Dim Dim DATOS DATOS As As New New SqlDataAdapter SqlDataAdapter(("detalle_orden" "detalle_orden",, conex) Dim Dim ds ds As As New Data. New Data.DataSet DataSet CommandType.StoredProcedure .StoredProcedure '*** '*** DATOS.SelectCommand.CommandType = CommandType "@e",, SqlDbType SqlDbType.Int).Value .Int).Value = DATOS.SelectCommand.Parameters.Add("@e" DATOS.SelectCommand.Parameters.Add( EmployeeIDTextBox.Text DATOS.Fill(ds, "empleado" "empleado")) DataGridView1.DataSource = ds.Tables("empleado" ds.Tables("empleado")) End End Sub Sub End Class Class End
Reporte seleccionar un año:
105
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
Public Class Public Class Form2 Form2 Private Sub Form2_Load(sender Form2_Load(sender As System. As System.Object Object,, e As System. As System.EventArgs EventArgs)) Handles Handles Private Sub MyBase.Load MyBase.Load Me.ANIOTableAdapter.Fill( .ANIOTableAdapter.Fill(Me Me.NorthwindDataSet2.ANIO) .NorthwindDataSet2.ANIO) Me End Sub End Private Sub Private Sub ComboBox1_SelectedIndexChanged(sender ComboBox1_SelectedIndexChanged(sender As As System. System.Object Object,, e As As System.EventArgs System. EventArgs)) Handles Handles ComboBox1.SelectedIndexChanged ComboBox1.SelectedIndexChanged Me.producvendiTableAdapter.Fill( .producvendiTableAdapter.Fill(Me Me.NorthwindDataSet4.producvendi, .NorthwindDataSet4.producvendi, Me ComboBox1.SelectedValue) Me Me.ReportViewer1.RefreshReport() .ReportViewer1.RefreshReport() End End Sub End Class End
Seleccionando el cliente:
106
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
Public Class Public Class Form3 Form3 Private Sub Form3_Load(sender Form3_Load(sender As System. As System.Object Object,, e As System. As System.EventArgs EventArgs)) Handles Handles Private Sub MyBase.Load MyBase.Load Me Me.MONTOSTableAdapter.Fill( .MONTOSTableAdapter.Fill(Me Me.NorthwindDataSet9.MONTOS) .NorthwindDataSet9.MONTOS) Me.CustomersTableAdapter.Fill( Me .CustomersTableAdapter.Fill(Me Me.NorthwindDataSet5.Customers) .NorthwindDataSet5.Customers) Me Me.ReportViewer1.RefreshReport() .ReportViewer1.RefreshReport() End Sub End Sub Private Sub Sub ComboBox1_SelectedIndexChanged(sender ComboBox1_SelectedIndexChanged(sender As As System. System.Object Object,, e As As Private EventArgs)) Handles Handles ComboBox1.SelectedIndexChanged ComboBox1.SelectedIndexChanged System.EventArgs System. Me Me.CLIENTESTableAdapter.Fill( .CLIENTESTableAdapter.Fill(Me Me.NorthwindDataSet7.CLIENTES, .NorthwindDataSet7.CLIENTES, CChar CChar(ComboBox1.SelectedValue)) (ComboBox1.SelectedValue)) Me Me.ReportViewer1.RefreshReport() .ReportViewer1.RefreshReport() End Sub End Sub End End Class
107
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
Hacer un gráfico de número de productos filtrado por categoría:
Public Public Class Class Form4 Form4 Private Sub Form4_Load(sender Form4_Load(sender As System. As System.Object Object,, e As System. As System.EventArgs EventArgs)) Handles Handles Private Sub MyBase.Load MyBase.Load Me.MONTOSTableAdapter.Fill( .MONTOSTableAdapter.Fill(Me Me.NorthwindDataSet9.MONTOS) .NorthwindDataSet9.MONTOS) Me Me.ReportViewer1.RefreshReport() .ReportViewer1.RefreshReport() Me End End Sub Sub End Class End
108
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
Reporte de los productos:
Public Public Class Class Form5 Form5 Private Sub Form5_Load(sender Form5_Load(sender As System. As System.Object Object,, e As System. As System.EventArgs EventArgs)) Handles Handles Private Sub MyBase.Load MyBase.Load Me.PCTableAdapter1.Fill( .PCTableAdapter1.Fill(Me Me.NorthwindDataSet11.PC) .NorthwindDataSet11.PC) Me Me Me.PCTableAdapter.Fill( .PCTableAdapter.Fill(Me Me.NorthwindDataSet10.PC) .NorthwindDataSet10.PC) Me.ReportViewer1.RefreshReport() .ReportViewer1.RefreshReport() Me End End Sub Sub End End Class
109
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
Pasar un parámetro de clientete
110
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
Public Class Public Class Form6 Form6 Private Sub Form6_Load(sender Form6_Load(sender As System. As System.Object Object,, e As System. As System.EventArgs EventArgs)) Handles Handles Private Sub MyBase.Load MyBase.Load Me.CustomersTableAdapter.Fill( .CustomersTableAdapter.Fill(Me Me.NorthwindDataSet13.Customers) .NorthwindDataSet13.Customers) Me End End Sub Sub Private Private Sub Sub ComboBox1_SelectedIndexChanged(sender ComboBox1_SelectedIndexChanged(sender As As System. System.Object Object,, e As As EventArgs)) Handles Handles ComboBox1.SelectedIndexChanged ComboBox1.SelectedIndexChanged System.EventArgs System. Me.CLIENTITableAdapter.Fill( .CLIENTITableAdapter.Fill(Me Me.NorthwindDataSet14.CLIENTI, .NorthwindDataSet14.CLIENTI, Me ComboBox1.SelectedValue) Me Me.ReportViewer1.RefreshReport() .ReportViewer1.RefreshReport() End Sub End Sub End End Class
Hacer un formulario donde se muestren las conferencias, los participantes, asistentes y un gráfico:
111
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
Reporte1:
Reporte2:
Reporte3:
112
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
Reporte4:
Código: Public Class Public Class Form1 Form1 Private Sub Form1_Load(sender Form1_Load(sender As As System. System.Object Object,, e As As System. System.EventArgs EventArgs)) Handles Handles Private Sub MyBase.Load MyBase.Load Me Me.ASISXCTableAdapter.Fill( .ASISXCTableAdapter.Fill(Me Me.Asistencia_Semana_SistémicaDataSet5.ASISXC) .Asistencia_Semana_SistémicaDataSet5.ASISXC) Me Me.CONFERENCIASTableAdapter1.Fill( .CONFERENCIASTableAdapter1.Fill(Me Me.Asistencia_Semana_SistémicaDataSet3.CONFERE .Asistencia_Semana_SistémicaDataSet3.CONFERE NCIAS)
113
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
Me.CONFERENCIASTableAdapter.Fill(Me Me.CONFERENCIASTableAdapter.Fill( Me.Asistencia_Semana_SistémicaDataSet1.CONFERE .Asistencia_Semana_SistémicaDataSet1.CONFERE NCIAS) Me.PARTICIPANTESTableAdapter.Fill( Me.PARTICIPANTESTableAdapter.Fill(Me Me.Asistencia_Semana_SistémicaDataSet.PARTICIPA .Asistencia_Semana_SistémicaDataSet.PARTICIPA NTES) Me.ReportViewer1.RefreshReport() Me.ReportViewer1.RefreshReport() Me.ReportViewer2.RefreshReport() Me.ReportViewer2.RefreshReport() Me.ReportViewer4.RefreshReport() Me.ReportViewer4.RefreshReport() End End Sub Sub Private Sub Sub ComboBox1_SelectedIndexChanged(sender ComboBox1_SelectedIndexChanged(sender As As System. System.Object Object,, e As As Private EventArgs)) Handles Handles ComboBox1.SelectedIndexChanged ComboBox1.SelectedIndexChanged System.EventArgs System. Me Me.ASISTableAdapter.Fill( .ASISTableAdapter.Fill(Me Me.Asistencia_Semana_SistémicaDataSet2.ASIS, .Asistencia_Semana_SistémicaDataSet2.ASIS, ComboBox1.SelectedValue) Me Me.ReportViewer3.RefreshReport() .ReportViewer3.RefreshReport() End Sub End Sub End End Class
Una consulta que nos lleve a otro formulario: Formulario 1: o
114
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
Imports System.Data.SqlClient Imports System.Data.SqlClient Public Class Form2 Form2 Public Class Private Private Sub Sub Form2_Load(sender Form2_Load(sender As System. As System.Object Object,, e As System. As System.EventArgs EventArgs)) Handles Handles MyBase.Load MyBase.Load Me Me.ProductsTableAdapter.Fill( .ProductsTableAdapter.Fill(Me Me.NorthwindDataSet.Products) .NorthwindDataSet.Products) End Sub End Sub Private Sub Sub DataGridView1_CellContentDoubleClick(sender DataGridView1_CellContentDoubleClick(sender As As Object, Object, e As As Private DataGridViewCellEventArgs)) Handles Handles System.Windows.Forms.DataGridViewCellEventArgs System.Windows.Forms. DataGridView1.CellContentDoubleClick Dim Dim detalle detalle As As New New SqlDataAdapter( SqlDataAdapter("SELECT OD.OrderID, OD.UnitPrice, OD.Quantity, P.ProductName FROM [Order Details] OD INNER JOIN Products P ON OD.ProductID = P.ProductID WHERE P.ProductNAME=@P", P.ProductNAME=@P", conex) Dim DB DB As As New Data. New Data.DataSet DataSet Dim detalle.SelectCommand.Parameters.Add("@P" detalle.SelectCommand.Parameters.Add( "@P",, SqlDbType.NVarChar, SqlDbType.NVarChar, 40).Value = DataGridView1.Rows(e.RowIndex).Cells(1).Value "detalle")) detalle.Fill(DB, "detalle" Form3.DataGridView1.DataSource = DB.Tables("detalle" DB.Tables( "detalle")) Form3.Show() .Show() Form3 End Sub End Sub End Class End Formulario2: o
115
Estrada Aguilar, Karen Johana |
PROGRAMACIÓN APLICADA I
Manual de Visual Basic Parte II 2012 2012
Imports System.Data.SqlClient Imports System.Data.SqlClient Public Class Form2 Form2 Public Class Private Sub Form2_Load(sender Form2_Load(sender As System. As System.Object Object,, e As System. As System.EventArgs EventArgs)) Handles Handles Private Sub MyBase.Load MyBase.Load Me.ProductsTableAdapter.Fill( .ProductsTableAdapter.Fill(Me Me.NorthwindDataSet.Products) .NorthwindDataSet.Products) Me End Sub End Sub Private Private Sub Sub DataGridView1_CellContentDoubleClick(sender DataGridView1_CellContentDoubleClick(sender As As Object, Object, e As As DataGridViewCellEventArgs)) Handles Handles System.Windows.Forms.DataGridViewCellEventArgs System.Windows.Forms. DataGridView1.CellContentDoubleClick Dim Dim detalle detalle As As New New SqlDataAdapter( SqlDataAdapter("SELECT OD.OrderID, OD.UnitPrice, OD.Quantity, P.ProductName FROM [Order Details] OD INNER JOIN Products P ON OD.ProductID = P.ProductID WHERE P.ProductNAME=@P", P.ProductNAME=@P", conex) Dim Dim DB DB As As New Data. New Data.DataSet DataSet detalle.SelectCommand.Parameters.Add("@P" detalle.SelectCommand.Parameters.Add( "@P",, SqlDbType.NVarChar, SqlDbType.NVarChar, 40).Value = DataGridView1.Rows(e.RowIndex).Cells(1).Value detalle.Fill(DB, "detalle" "detalle")) Form3.DataGridView1.DataSource = DB.Tables("detalle" DB.Tables( "detalle")) Form3 Form3.Show() .Show() End Sub End Sub End End Class
116