MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

Slides:



Advertisements
Presentaciones similares
Cable & Wireless Panamá. Entrar a Inicio, Programas y buscar Windows Live.
Advertisements

PRÁCTICA A REALIZAR EN EL CURSO DE ADO.NET
CREATE VIEW nombre [ ( columna [,...n ] ) ] AS sentencia_select [ WITH CHECK OPTION ] 1.nombre Es el nombre de la vista. 2.Se debe tener permisos CREATE.
INSTRUCTOR: LI Ramiro Robles Villanueva
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.
Subrutinas y Funciones Leonel Morales Díaz Ingeniería Simple Disponible en: Copyright.
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?
Como Configurar el Internet
PLEASE READ (hidden slide) This template uses Microsofts corporate font, Segoe Segoe is not a standard font included with Windows, so if you have not.
U SING FOLKTALES IN THE CLASSROOM C IRCLE M AP The gods A mermaid An Inca.
U SING FOLKTALES IN THE CLASSROOM. L AS I SLAS E NCANTADAS.
Macros en Excel Seminario I. Definición Excel es un programa que tiene un gran potencial, pero la mayoría de la gente lo maneja de una forma muy simple,
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.
78 – Digitizing Echograms and Merging with Position Data
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
MSQL OPERADORES BIT A BIT & a & b Operador de BIT AND. I a l b Operador de BIT OR. < < a >
1) Penélope Cruz es actriz mexicana ……………………………………….. 2) Nació en setiembre ………………………………………………………….. 3) Tiene 23 años …………………………………………………………… 4) Nació
Bases de Datos Espaciales SPATIAL QUERY LANGUAGES
Invocar procedimientos almacenados con Microsoft ADO.NET
Acceso a datos con Microsoft ADO.NET
SQL Server 2005 ADO.NET Javier Fernández Rodríguez Noviembre 2005, Sevilla Javier Fernández Rodríguez Noviembre 2005, Sevilla.
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.
These are my books. Those are yours. I saw their car in the garage. Have you seen ours? I ate my cookie yesterday. Did George eat ______? We went to our.
¿Cómo te llamas? ¿De dónde eres?
INTEGRIDAD, INTEGRIDAD REFERENCIAL
LUIS GONZALES SÁNCHEZ RESPONSABLE PROCESO DE REGISTRO DE DNI DE ESTUDIANTES UNIDAD DE GESTIÓN EDUCATIVA LOCAL LAMAS UNIDAD EJECUTORA 305.
ERASMO AGUILAR SIG FARQ UNI
César Gutiérrez. BASES DE DATOS. INTRODUCCIÓN 2 DEFINICIÓN: Una base de datos es una colección de datos relacionados entre sí. Dichos datos se almacenan.
G OBIERNO DEL E STADO DE S ONORA MANUAL PARA SUPERVISORES SISTEMA DE ADMINISTRACIÓN VIRTUAL DEL PROGRAMA ESCUELAS DE CALIDAD SECRETARÍA DE E DUCACIÓN Y.
Visual basic Curso de Habilitación Laboral IV. ¿Qué es Visual Basic Visual Basic es uno de los tantos lenguajes de programación que podemos encontrar.
Un constructor es un método que inicia un objeto inmediatamente después de su creación. De esta forma nos evitamos el tener que iniciar las variables.
Lo primero que tenemos que tener claro es donde vamos a instalar el ordenador. Es cierto que no siempre se puede elegir el sitio, pero mientras que sea.
Nombre:Nº de Control: María del Carmen Raygoza Hernández Judith Itzel Requejo Hernández
Las consultas. Son cuadros de información generados a partir de datos relacionados encontrados en otras tablas que se utilizan para filtrar, ver, modificar.
Procedimientos Almacenados y Disparadores
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.
FACULTAD DE INGENIERIA INDUSTRIAL Y DE SISTEMAS PROTOTIPO, CODIFICACION DEL SISTEMA Y CONECTIVIDAD MBA CARLOS ZORRILLA VARGAS.
SQL Base de Datos LENGUAJES DE CONSULTA AR y CR no pueden ser tomados como base para implementar porque: Poseen sintaxis compleja No permiten.
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.
Antonio Gámir TSP – Windows Client Microsoft Ibérica.
Introducción ADO .Net.
Oracle y Java Continuación *
Herramientas de Oracle para realizar Tuning de Sentencias SQL
Seminario de Lenguajes A – Opción Ada Seminario de Lenguajes A – Opción Ada – Raúl Champredonde1 Overloading de subprogramas procedure Put(Item: in integer;
Seminario de Lenguajes A – Opción Ada
Bases de Datos Relacionales Preparó: Ismael Castañeda Fuentes Fuentes:Manuales Sybase Manuales SQL Server Manuales Oracle BATCHS.
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.
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.
16/04/ Sesión 11 Funciones y procedimientos Ing. Ricardo Inquilla.
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.
Estructura de Repetición en Visual Basic
Control, adquisición y monitoreo con Arduino y Visual Basic .net
MYSQL SQL: Lenguaje de consulta estructurado. Es un lenguaje de programación para trabajar con BD relacionadas, entre las cuales tenemos MYSQL, ORACLE,
Tipos de datos en MYSQL YEAR: Año. “YYYY” o “YY”
BASE DE DATOS IUPSM CLASE PRACTICA. PROF. ING. JOSE L GUZMAN H.
Lenguaje C++ Problemas.
Oracle Pl/SQl Developer – Nivel 1
Al hacer esto tenemos que tener en Cuentacuentos text box hay que hacer en la nuestra tuvimos que hacer 8 labels.
ENTERPRISE ARCHITECTURE UCV –TRUJILLO Ing. Mg. Daniel Antonio Miranda Acuña.
Transcripción de la presentación:

MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO Ado.net

DIRIGIDO A: Este manual esta dirigido a

txtclave txtNombre txtFecha btnprimero txtinversion btnanterior Vamos a crear un sistema para llevar el control de las obras municipales, supongamos que tenemos el siguiente formulario: Noregistros es una etiqueta llamada etposicion txtclave txtNombre txtFecha btnprimero txtinversion btnanterior btnsiguiente btnAgregar btnultimo btnguardar btneliminar etposicion btnimprimir GridView1 btnsalir

Nombres de las cajas de Texto, botones y etiqueta Txtclave Txtnombre Txtinversion Txtfecha btnAgregar btnGuardar btnImprimir btnEliminar btnSalir etposicion

Lo primero que debemos hacer es nuestra base de datos en acces o sql server según se necesite, en nuestro caso lo haremos en acces, entramos a acces y hacemos los siguientes pasos:

Guardamos nuestra base de datos, a la cual le ponemos obras en nuestra carpeta, en este caso se guardo en la carpeta obras en la unidad c.

Crear tabla Obras, damos doble clic en Id y cambiamos el nombre del campo a clave y cambiamos el tipo de dato de Auto numérico a numérico.

Agregamos los siguientes campos, nombre, fecha e inversión:

Para cambiar los tipos de datos es en la pestaña mostrada a continuación: Declaramos Clave auto numérico, nombre texto, fecha texto y inversión de tipo moneda.

Guardamos nuestra tabla y le ponemos el nombre de Datos.

Antes de salir de acces debemos de guardar nuestra base de datos con compatibilidad de Office 2002-2003

En visual studio hacemos lo siguiente: Buscamos un control llamado OleDbDataAdapter para hacer la conexión con acces. Si no esta en las herramientas tenemos que agregar el control. Para agregarlo hacer lo siguiente: clic derecho sobre caja de herramientas y elegir choose items

Seleccionar los siguientes controles para agregarlos:

Ahora agregamos un OleDbDataAdapter a nuestro formulario y seleccionamos New Connection.

En esta pantalla debemos de cambiar el DataSource, seleccionamos Change para elegir el driver de Microsoft Acces..

Seleccionamos Microsoft Acces Database

Seleccionamos nuestra base de datos y en la siguiente pantalla damos clic en ok:

Al tener nuestra conexión damos clic en siguiente:

Seleccionamos use sql statements y damos clic en siguiente:

Damos clic en QueryBuilder

Aquí agregamos la tabla Datos.

Seleccionamos todas las columnas damos clic en Ok:

Nos queda la consulta de la siguiente manera y damos clic en Siguiente:

Damos clic en finalizar

Luego generamos un Dataset y damos clic en ok.

Debemos de tener en la parte inferior nuestro Oledbdataadapter, Oledbconnection y dataset11

A continuación vincularemos las cajas de texto con nuestro dataset A continuación vincularemos las cajas de texto con nuestro dataset. Damos clic derecho a la caja de texto del campo clave y buscamos la propiedad Databinding, seleccionamos la porpiedad text y seleccionamos la opción como se muestra en la figura: para cada caja de texto seleccionamos el campo correspondiente.

Cambiar el nombre a Dataset11 por DsObras y al OleDbDataAdapter por DaObras

Código del botón Siguiente Código del botón Primero donde DsObras es el nombre del Dataset y Datos es el nombre de la tabla. BindingContext(DsObras, “Datos").Position = 0 MostrarPosicion() Código del botón Siguiente BindingContext(DsObras, “Datos").Position += 1 MostrarPosicion() Código del botón Anterior BindingContext(DsObras, “Datos").Position -= 1 MostrarPosicion() Código del botón Ultimo BindingContext(DsObras, “Datos").Position = _ BindingContext(DsObras, “Datos").Count - 1 MostrarPosicion()

Agregamos a nuestro código el procedimiento de MostrarPosicion Private Sub MostrarPosicion() Dim bmBase As BindingManagerBase = BindingContext(DsObras, “Datos") Dim iTotal As Integer = bmBase.Count 'total registros Dim iPos As Integer If iTotal = 0 Then etPosicion.Text = "No registros" Else iPos = bmBase.Position + 1 'número (1, 2, ...) de registro 'Mostrar información en la etiqueta etPosicion.Text = iPos.ToString & " de " & iTotal.ToString End If End Sub

Código del botón Agregar Me.txtClave.Text = "" Me.txtNombre.Text = "" Me.txtFecha.Text = " " Me.txtInversion.Text = "" Me.txtClave.Focus()

Código del botón Guardar Dim miTabla As DataTable = DSOBRAS.Datos Dim cfilas As DataRowCollection = miTabla.Rows Dim nuevaFila As DataRow Dim nombre As String Dim clave As String Dim inversion As Double Dim fecha As String clave = Me.txtClave.Text nombre = Me.txtNombre.Text inversion = Me.txtInversion.Text fecha = Me.txtFecha.Text Try 'Nueva fila nuevaFila = miTabla.NewRow 'Columnas de la tabla nuevaFila.Item("CLAVE") = clave nuevaFila.Item("NOMBRE") = nombre nuevaFila.Item("Inversion") = inversion nuevaFila.Item("fecha") = fecha MsgBox("Registro agregado") cfilas.Add(nuevaFila) Catch ex As System.Data.ConstraintException REM Capturar posible error por clave duplicada (teléfono) MessageBox.Show("ERROR DE CLAVE DUPLICADA") End Try DaObras.Fill(DSOBRAS) MostrarPosicion() If (DSOBRAS.HasChanges()) Then DaObras.Update(DSOBRAS) MessageBox.Show("Origen de datos actualizado") End If Me.Close()

Código del botón eliminar Dim bmBase As BindingManagerBase = BindingContext(DSOBRAS, "datos") 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() MostrarPosicion() End If

Código de las cajas de texto en el evento keypress para avanzar con un enter a otra caja de texto. Código de la caja de texto txtclave en el evento keypress If e.KeyChar = Chr(13) Then txtNombre.Focus() End If Código de la caja de texto txtnombre en el evento keypress If e.KeyChar = Chr(13) Then txtfecha.Focus() End If Código de la caja de texto txtfecha en el evento keypress If e.KeyChar = Chr(13) Then txtfecha.Focus() End If Código de la caja de texto txtinversion en el evento keypress If e.KeyChar = Chr(13) Then Btnguardar.enabled=true btnguardar.Focus() End If

Código del evento load del formulario: btnGuardar.Enabled = False DSOBRAS.Clear() DaObras.Fill(DSOBRAS) MostrarPosicion()

Código del botón eliminar Dim bmBase As BindingManagerBase = BindingContext(DSOBRAS, "datos") 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() MostrarPosicion() End If

Para imprimir a excel debemos de agregar una referencia de la siguiente manera:

Agregar las referencias que se encuentran en la carpeta obras.

Código del botón 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 = "CLAVE" .Range("A1").Font.Bold = True .Range("B1").Value = "NOMBRE" .Range("B1").Font.Bold = True .Range("C1").Value = "FECHA" .Range("C1").Font.Bold = True .Range("D1").Value = "INVERSION" .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 DsObras.Tables(0).Rows .Range("A" & i.ToString).Value = dr("CLAVE") .Range("B" & i.ToString).Value = dr("NOMBRE") .Range("C" & i.ToString).Value = dr("FECHA") .Range("D" & i.ToString).Value = dr("INVERSION") i += 1 Next End With

Vincular el gridview con la base de datos en la propiedad Datasource y Datamember.

CONSULTAS: Agregue y diseñe el siguiente formulario.

Nombres de los controles del formulario consultas: rbtNombresa cmdNames rbtNombresd cboNombres cmdSort gridobras

Declaraciones de variables en el formulario de consultas: Dim conn As String = _ "Provider=Microsoft.jet.oledb.4.0;data source=C:\OBRAS\OBRAS.mdb;" Dim DVobras 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 DVobras.RowFilter = strFilter 'Display the sorted and filtered view in the datagrid Gridobras.DataSource = DVobras '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 DVobras.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 DVobras.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 DVobras.Sort = strSort 'Display the view in the datagrid Me.Gridobras.DataSource = DVobras

Código del formulario de consultas en el evento load Dim amigosConnection As New OleDbConnection(conn) Dim productadapter As New OleDbDataAdapter("SELECT clave, nombre, fecha, inversion from Datos", amigosConnection) Dim dsOBRAS As New DataSet() Dim cmd As OleDbCommand Dim idrfc As String amigosConnection.Open() productadapter.Fill(dsOBRAS, "DATOS") ''create the dataview; use a constructor to specify '' the sort, filter criteria for performance purposes DVobras = New DataView(dsOBRAS.Tables("DATOS"), DEFAULT_FILTER, DEFAULT_SORT, DataViewRowState.OriginalRows) ' Bind the DataGrid to the dataview created above Gridobras.DataSource = DVobras ''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>"

POR SU ATENCIÓN GRACIAS.