PRÁCTICA A REALIZAR EN EL CURSO DE ADO.NET

Slides:



Advertisements
Presentaciones similares
INSTRUCTOR: LI Ramiro Robles Villanueva
Advertisements

Mr. Redaelli OnlineTaco.com. To Have - Tener Yo tengo – I have Tú tienes – You have (Informal) Usted tiene – You have (Formal) El tiene – He has Ella.
ALMACENAMIENTO Y OBTENCIÓN DE DATOS CON ADO.NET. Entender ADO.NET Tres niveles: Tres niveles: El almacenamiento físico de datos. Puede ser una base de.
Visual Basic for Applications 3 de Mayo de Archivo en Excel Son 600 nombres Separar las columnas Separar los nombres en varias columnas ¿Cómo hacerlo?
Noviembre– La lección tres. cgaisar arcasigaasar carga caracasagasasaca caigaarcascasarsacargracias.
USING THE INTERNET. 2 Concept 6.1 What Is the Internet? The Internet is millions of computers from all parts of the world connected so that they can communicate.
2003 HYPACK MAX Training Seminar1 Sample Case la Entrada manual de Datos de la Línea de la costa El Metodo de MANUAL –DIG Objectos –Boya (Roja)
2003 HYPACK MAX Training Seminar1 Sample Belgium Test Inputting Tag Line information into HYPACK® MAX In the old days, a Tag Line was anchored to.
2003 HYPACK MAX Training Seminar Programas externos Una alternativa practica a usar el usual menú de Windows® Abra sus programas favoritos sin minimizar.
Hagan Ahora ¿Qué te gusta hacer?.
Delete en tablas: titulacion. Puedo eliminar cualquier fila de una tabla? Restriccion de integridad: Restrict/Cascade.
Conceptos Básicos del lenguaje de programación COBOL
Estructura de Selección en Visual Basic
Introducción a Windows Forms
Invocar procedimientos almacenados con Microsoft ADO.NET
Acceso a datos con Microsoft ADO.NET
El Verbo GUSTAR En español gustar means to be pleasing In English, the equivalent is to like.
Speaking Exercises 1.Save this program as speaking exercise #1YOUR NAME in the M drive 2.Read each question out loud into your microphone, and then reply.
Gramática 2.1 Question Formation Colors
A Comer Vamos a Poner la Mesa.
¿Cómo te llamas? ¿De dónde eres?
MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO
INTEGRIDAD, INTEGRIDAD REFERENCIAL
Nombre:Nº de Control: María del Carmen Raygoza Hernández Judith Itzel Requejo Hernández
Ud.8 Aplicaciones ofimáticas Índice del libro Índice del libro.
Procedimientos Almacenados y Disparadores
Table of Contents Help How to Find Clip Art How to Export Clip Art How to Print Clip Art Talk About Activities UNIDAD 1 Lección 1 andar en patineta alquilar.
ALC 11 lunes el 26 de septiembre. Bienvenida lunes el 26 de septiembre Front row face the back row. Back row will read the words on the screen in the.
Español 1 18 y 19 de septiembre de Escribe los meses que combinan con las estaciónes. (Write the months that match with the seasons.) El otoño-
To bring together a group of lawyers, realtors, tax companies, mortgage companies and economy experts and participate in the first fair thats main purpose.
Subject Pronouns and AR verb conjugations As you click through this powerpoint, you will need to answer the questions on your worksheet. At the end, you.
FACULTAD DE INGENIERIA INDUSTRIAL Y DE SISTEMAS PROTOTIPO, CODIFICACION DEL SISTEMA Y CONECTIVIDAD MBA CARLOS ZORRILLA VARGAS.
PL/SQL Francisco Moreno Universidad Nacional. Funciones Si un procedimiento tiene solo un parámetro de salida, se puede remplazar por una función y esta.
ADO.NET Daniel A. Seara Director Regional MSDN Buenos Aires – ARGENTINA NDSoft.
Facilitando la vida del desarrollador con Visual Studio 2005 Daniel A. Seara
Introducción ADO .Net.
Oracle y Java Continuación *
Describe the people or things below using the correct forms of the verb SER and the adjectives provided. EX: profesoras de matemáticas / divertido. Las.
HAZ AHORA / DO NOW Responde en frases completas: Por ejemplo: ¿Qué te gusta más, nadar o esquiar? Pues, me gusta más nadar. Pues, no me gusta ni nadar.
Administración de Servidores de Bases de Datos Bases de Datos de Usuarios Caso particular Adaptive Server Enterprise.
© 2013 Board of Regents of the University of Wisconsin System, on behalf of WIDA.
Editing Slides With Polaris Office, you can create new .ppt and .pptx presentations or edit your presentation with ease.
THOMSON SCIENTIFIC Updates for April Copyright 2006 Thomson Corporation 2 2 Actualizaciones Actualizaciones a las herramientas Refine y Analyze.
 1. Why should a person learn Spanish? Give at least 3 reasons in your explanation.  2. What Spanish experiences have you had? (None is not an option.
Please do the following: 1.Measure an arms length of yarn of the color you like and cut it. (arms length goes from finger tip of one had to fingertip of.
Derechos de Autor©2008.SUAGM.Derechos Reservados Sistema Universitario Ana G. Méndez División de Capacitación Basic Quality Tools CQIA Primer Section VII.
Dim VARIABLE As TIPODATO Dim int As Integer = 0 VARIABLE= InputBox(“Digite el Documento a buscar") While Not NOMBRETABLA.EOF And int = 0 If NOMBRETABLA.Fields(0).Value.
Laboratorio Informática II Clase 5 Excel Controles Active X.
La Familia Click to Begin. Hola! Me llamo Juan. This activity is all about mi familia. On each page, read the family member word at the top and then click.
Estructura de Repetición en Visual Basic
Read through the following slides and fill out your study guide Fundamentos de Word : los menús del inserto, revisar y ver Leer a través de las siguientes.
Un juego de adivinanzas: ¿Dónde está el tesoro? A1B1C1D1E1F1 A4B4C4D4E4F4 A2B2C2D2E2F2 A5B5C5D5E5F5 A3B3C3D3E3F3 A6B6C6D6E6F6 Inténtalo de nuevo Inténtalo.
3 Ways to Record PowerPoint From within PowerPoint From within Camtasia Studio.
2 Ways to Record PowerPoint From within PowerPoint From within Camtasia Studio.
Estructura de Selección en Visual Basic
Estructura General de las Instrucciones en Visual Basic
3 Ways to Record PowerPoint From within PowerPoint From within Camtasia Studio.
BASE DE DATOS IUPSM CLASE PRACTICA. PROF. ING. JOSE L GUZMAN H.
CREAR INFORME EN CRYSTAL REPORTS
2 Ways to Record PowerPoint From within PowerPoint From within Camtasia Studio.
Al hacer esto tenemos que tener en Cuentacuentos text box hay que hacer en la nuestra tuvimos que hacer 8 labels.
Excel Macros Formularios.
Record a Presentation Use the Camtasia Add-in to record your presentations. Start by going to the Add-ins tab.
A PowerPoint Template Your Presentation Name. This text is a placeholder Main Content Page Layout 2 Copyright 2009.
JKSimMet Software (windows & buttons) Split Engineering Chile Ltda. General Salvo #331 oficina 201 Casilla Sucursal Panorámico Providencia – Santiago,
2 Ways to Record PowerPoint From within PowerPoint From within Camtasia Studio.
Welcome to PowerPoint gdskcgdskfcbskjc. Designer helps you get your point across PowerPoint Designer suggests professional designs for your presentation,
TABLET INFORMATION SUBMIT A Presentation Template.
ENTERPRISE ARCHITECTURE UCV –TRUJILLO Ing. Mg. Daniel Antonio Miranda Acuña.
Transcripción de la presentación:

PRÁCTICA A REALIZAR EN EL CURSO DE ADO.NET SISTEMA AGENDA.NET

Crear un nuevo proyecto

DISEÑAR EL SIGUIENTE FORMULARIO DE INICIO Para ello debemos agregar un Main Menu, un ToolBar un ImageList, un Status Bar, un Datetimepicker y un Picture Box

Código para que funcione el ToolBar Private Sub ToolBar1_ButtonClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ToolBarButtonClickEventArgs) Handles ToolBar1.ButtonClick Select Case ToolBar1.Buttons.IndexOf(e.Button) Case 0 Dim x As New Datos() x.Visible = True Case 1 MsgBox("EN CONSTRUCCIÓN") Case 2 Case 3 End End Select End Sub

Código para mandar llamar a otro formulario Dim x As New Datos() x.Visible = True

Crear la siguiente base de datos en Guardarla en la misma carpeta del proyecto

Diseñar el formulario de altas

Nombres de los controles txtNombre txtTelefono txtMail txtCumple btnPrimero btnAnterior btnSiguiente btnUltimo btnAgregar btnGuardar btnBorrar btnImprimir btnSalir Datagrid1

Crear la conexión a la base de datos y seleccionar el proveedor de datos

Seleccionar la base de datos y probar la conexión

Conexión a la base de datos

Crear la OleDbConnection y el OleDbDataAdapter y cambiarle el nombre a oledbconnagenda y daAgenda en la propiedad name

Agregar un conjunto de datos o Dataset al proyecto, dando clic derecho sobre el daAgenda

Cambiamos el nombre al dataset por dsAgenda

Vinculamos cada uno de los controles en la propiedad DataBindings, seleccionando el dataset, tabla y campo correspondiente.

Vinculamos el Datagrid con el origen de datos correspondiente en la propiedad Datasource.

Llenamos los controles con la base de datos de la siguiente manera:

Código para llenar los controles: Llenamos el dataAdapter con el Dataset Private Sub frmDatos_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Me.dsAgenda.Clear() daAgenda.Fill(dsAgenda) End Sub

Código para los siguientes botones: Boton primero: BindingContext(DsAgenda, “Agenda").Position = 0 MostrarPosicion() Boton Anterior: BindingContext(dsAgenda, "Agenda").Position -= 1 MostrarPosicion() Boton Siguiente BindingContext(DsAgenda, “Agenda").Position += 1 MostrarPosicion() Boton Ultimo BindingContext(DsAgenda, “Agenda").Position = _ BindingContext(DsAgenda, “Agenda").Count - 1 MostrarPosicion()

Código mostrar posición Private Sub MostrarPosicion() Dim bmBase As BindingManagerBase = BindingContext(DsAgenda, “Agenda") Dim iTotal As Integer = bmBase.Count 'total registros Dim iPos As Integer If iTotal = 0 Then lblRegistros.Text = "No registros" Else iPos = bmBase.Position + 1 'número (1, 2, ...) de registro 'Mostrar información en la etiqueta lblRegistros.Text = iPos.ToString & " de " & iTotal.ToString End If End Sub

Ahora si podemos desplazarnos a los diferentes registros a través de los botones programados.

Código para el botón Agregar Private Sub btnAgregar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAgregar.Click Me.txtNombre.Text = "" Me.txtCumple.Text = "" Me.txtMail.Text = "" Me.txtTelefono.Text = "" Me.txtNombre.Focus() End Sub

Código para el bóton Guardar Dim miTabla As DataTable = dsAgenda.Agenda Dim cfilas As DataRowCollection = miTabla.Rows Dim nuevaFila As DataRow Dim nombre As String Dim telefono As String Dim email As String Dim cumple As String nombre = Me.txtNombre.Text telefono = Me.txtTelefono.Text email = Me.txtMail.Text cumple = Me.txtCumple.Text Try 'Nueva fila nuevaFila = miTabla.NewRow 'Columnas de la tabla nuevaFila.Item("NOMBRE") = nombre nuevaFila.Item("TELEFONO") = telefono nuevaFila.Item("EMAIL") = email nuevaFila.Item("CUMPLE") = cumple MsgBox("Registro agregado") cfilas.Add(nuevaFila) Catch ex As System.Data.ConstraintException MessageBox.Show("ERROR DE CLAVE DUPLICADA") End Try daAgenda.Fill(dsAgenda) If (dsAgenda.HasChanges()) Then daAgenda.Update(dsAgenda) MessageBox.Show("Origen de datos actualizado") End If

Código para eliminar un registro Dim bmBase As BindingManagerBase = BindingContext(dsAgenda, "Agenda") Dim vistaFilaActual As DataRowView Dim NL As String = Environment.NewLine If (MessageBox.Show("¿Desea borrar este registro?" & NL, _ "Buscar", MessageBoxButtons.YesNo, _ MessageBoxIcon.Question) = DialogResult.Yes) Then vistaFilaActual = bmBase.Current vistaFilaActual.Row.Delete() End If If (dsAgenda.HasChanges()) Then daAgenda.Update(dsAgenda) MessageBox.Show("Origen de datos actualizado")

Agregar una referencia a Excel para exportar los datos.

Código para imprimir a Excel Dim excelApp As New excel.Application() Dim excelBook As Excel.Workbook = excelApp.Workbooks.Add Dim excelWorksheet As Excel.Worksheet = _ CType(excelBook.Worksheets(1), Excel.Worksheet) excelApp.Visible = True With excelWorksheet ' Set the column headers and desired formatting for the spreadsheet. .Columns().ColumnWidth = 21.71 .Range("A1").Value = "NOMBRES" .Range("A1").Font.Bold = True .Range("B1").Value = "TELEFONO" .Range("B1").Font.Bold = True .Range("C1").Value = "EMAIL" .Range("C1").Font.Bold = True .Range("D1").Value = "CUMPLEAÑOS" .Range("D1").Font.Bold = True ' Start the counter on the second row, following the column headers Dim i As Integer = 2 ' Loop through the Rows collection of the DataSet and write the data ' in each row to the cells in Excel. Dim dr As DataRow For Each dr In dsAgenda.Tables(0).Rows .Range("A" & i.ToString).Value = dr("nombre") .Range("B" & i.ToString).Value = dr("telefono") .Range("C" & i.ToString).Value = dr("email") .Range("D" & i.ToString).Value = dr("cumple") i += 1 Next End With

CONSULTAS: Agregue y diseñe el siguiente formulario.

Nombres de los controles del formulario consultas: cmdNames rbtNombresA rbtNombresD cboNombres cmdSort gridAmigos

CONSULTAS Imports System.Data.OleDb Agregar el siguiente código en la parte superior para importar las clases de la base de datos OleDb. Imports System.Data.OleDb Crear una conexión a la base de datos. Dim conn As String = _ "Provider=Microsoft.jet.oledb.4.0;data source=D:\EJEMPLO SEMANA ACADEMICA\AGENDA.mdb;"

Declaraciones en el formulario de consultas Imports System.Data.OleDb Dim conn As String = _ "Provider=Microsoft.jet.oledb.4.0;data source=D:\EJEMPLO SEMANA ACADEMICA\AGENDA.mdb;" Dim DVAmigos As DataView Protected Const DEFAULT_FILTER As String = "Nombre like '%'" Protected Const DEFAULT_SORT As String = "Nombre ASC, Nombre DESC" Protected Const NO_RECORDS_FOUND_MESSAGE As String = "No existen registros en ese criterio de busqueda." Protected Const CAPTION_TITLE As String = "Ordena y filtra en un Dataview" Protected Const NO_RECORDS_TO_SORT_MESSAGE As String = "No existen registros para ordenar." Protected Const CAPTION_ICON_BUTTON As MsgBoxStyle = CType(MsgBoxStyle.Information + MsgBoxStyle.OKOnly, MsgBoxStyle)

Código para realizar consultas en el botón cmdNames Dim strFilter As String 'Process the row filter criteria based on first character of the product name. ' if <ALL> was selected, show all rows in the grid, else show only ' those rows beginning with the selected letter. If cboNombres.Text = "<ALL>" Then strFilter = "Nombre like '%'" Else strFilter = "Nombre like '" & cboNombres.Text & "%'" End If DVAmigos.RowFilter = strFilter 'Display the sorted and filtered view in the datagrid gridAmigos.DataSource = DVAmigos 'Display the number of rows in the view 'lblRecords.Text = STATUS_MESSAGE & dvProducts.Count.ToString 'lblFilter.text = strFilter 'display a msgbox if no records were found that ' match the user criteria If DVAmigos.Count = 0 Then MsgBox(NO_RECORDS_FOUND_MESSAGE, CAPTION_ICON_BUTTON, CAPTION_TITLE)

Código para el botón cmdSort Dim strSort As String 'Only sort if the dataview currently has records If DVAmigos.Count = 0 Then MsgBox(NO_RECORDS_TO_SORT_MESSAGE, CAPTION_ICON_BUTTON, CAPTION_TITLE) Exit Sub End If 'Process the sort criteria selected for the view ' construct a sort string for the primary, secondary sort keys ' The Primary sort key is the UnitsInStock column, the ' secondary sort key is UnitsOnOrder column If rbtNombresA.Checked = True Then strSort = "Nombre ASC" Else strSort = "Nombre DESC" If rbtNombresD.Checked = True Then strSort = strSort & ", Nombre ASC" strSort = strSort & ", Nombre DESC" 'Apply the sort criteria to the dataview DVAmigos.Sort = strSort 'Display the view in the datagrid Me.gridAmigos.DataSource = DVAmigos

Código del formulario de consultas en el evento load Private Sub frmconsultas_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim amigosConnection As New OleDbConnection(conn) Dim productadapter As New OleDbDataAdapter("SELECT nombre, telefono, email, cumple from AGENDA", amigosConnection) Dim dsamigos As New DataSet() Dim cmd As OleDbCommand Dim idrfc As String amigosConnection.Open() productadapter.Fill(dsamigos, "AGENDA") ''create the dataview; use a constructor to specify '' the sort, filter criteria for performance purposes DVAmigos = New DataView(dsamigos.Tables("AGENDA"), DEFAULT_FILTER, DEFAULT_SORT, DataViewRowState.OriginalRows) ' Bind the DataGrid to the dataview created above gridAmigos.DataSource = DVAmigos ''Populate the combo box for productName filtering. '' Allow a user to select the first letter of products that they wish to view cboNombres.Items.AddRange(New Object() {"<ALL>", "A", "B", "C", "D", "E", "F", "G", _ "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}) cboNombres.Text = "<ALL>" End Sub

REPORTES CON CRYSTAL REPORT Diseñar el siguiente formulario: El control CrystalReportViewver debe de llamarse crv. Y debemos importar lo siguiente: Imports CrystalDecisions.CrystalReports.Engine

Código para los reportes, botón cargar reporte Dim tbCurrent As CrystalDecisions.CrystalReports.Engine.Table Dim tliCurrent As CrystalDecisions.Shared.TableLogOnInfo ' Create a report document instance to hold the report Dim Datos As New ReportDocument() Try ' Load the report crv.Visible = True Datos.Load("D:\EJEMPLO SEMANA ACADEMICA\AGENDA\REPORTE.rpt") crv.ReportSource = Datos ' Zoom viewer to fit to the whole page so the user can see the report crv.Zoom(2) Catch Exp As LoadSaveReportException MsgBox("Incorrect path for loading report.", _ MsgBoxStyle.Critical, "Load Report Error") Catch Exp As Exception MsgBox(Exp.Message, MsgBoxStyle.Critical, "General Error") End Try