MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

47
ADO.NET MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

description

MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO. Ado.net. DIRIGIDO A:. Este manual esta dirigido a. 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. - PowerPoint PPT Presentation

Transcript of MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

Page 1: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

ADO.NET

MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

Page 2: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

DIRIGIDO A:

Este manual esta dirigido a

Page 3: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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

txtFecha

txtNombre

txtinversionbtnprimerobtnanteriorbtnsiguiente

btnultimo

etposicion

btnAgregar

btnguardar

btneliminar

btnimprimir

btnsalirGridView1

Page 4: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

Nombres de las cajas de Texto, botones y etiqueta

TxtclaveTxtnombreTxtinversionTxtfechabtnAgregarbtnGuardarbtnImprimirbtnEliminarbtnSaliretposicion

Page 5: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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:

Page 6: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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.

Page 7: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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.

Page 8: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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

Page 9: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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.

Page 10: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

Guardamos nuestra tabla y le ponemos el nombre de Datos.

Page 11: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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

Page 12: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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

Page 13: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

Seleccionar los siguientes controles para agregarlos:

Page 14: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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

Page 15: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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

Page 16: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

Seleccionamos Microsoft Acces Database

Page 17: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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

Page 18: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

Al tener nuestra conexión damos clic en siguiente:

Page 19: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

Seleccionamos use sql statements y damos clic en siguiente:

Page 20: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

Damos clic en QueryBuilder

Page 21: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

Aquí agregamos la tabla Datos.

Page 22: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

Seleccionamos todas las columnas damos clic en Ok:

Page 23: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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

Page 24: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

Damos clic en finalizar

Page 25: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

Luego generamos un Dataset y damos clic en ok.

Page 26: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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

Page 27: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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.

Page 28: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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

Page 29: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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 SiguienteBindingContext(DsObras, “Datos").Position += 1MostrarPosicion()

Código del botón Anterior BindingContext(DsObras, “Datos").Position -= 1 MostrarPosicion()

Código del botón UltimoBindingContext(DsObras, “Datos").Position = _ BindingContext(DsObras, “Datos").Count - 1 MostrarPosicion()

Page 30: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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

Page 31: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

Código del botón Agregar

Me.txtClave.Text = "" Me.txtNombre.Text = "" Me.txtFecha.Text = " " Me.txtInversion.Text = "" Me.txtClave.Focus()

Page 32: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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()

Page 33: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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

Page 34: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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 keypressIf e.KeyChar = Chr(13) Then Btnguardar.enabled=true btnguardar.Focus() End If

Page 35: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

Código del evento load del formulario:

btnGuardar.Enabled = False DSOBRAS.Clear() DaObras.Fill(DSOBRAS) MostrarPosicion()

Page 36: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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

Page 37: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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

Page 38: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

Agregar las referencias que se encuentran en la carpeta obras.

Page 39: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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

Page 40: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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

Page 41: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

CONSULTAS: Agregue y diseñe el siguiente formulario.

Page 42: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

Nombres de los controles del formulario consultas:

cboNombres

rbtNombresa

rbtNombresd cmdSort

gridobras

cmdNames

Page 43: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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)

Page 44: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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) End If

Page 45: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

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" End If If rbtNombresd.Checked = True Then strSort = strSort & ", Nombre ASC" Else strSort = strSort & ", Nombre DESC" End If 'Apply the sort criteria to the dataview DVobras.Sort = strSort 'Display the view in the datagrid Me.Gridobras.DataSource = DVobras

Page 46: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

Código del formulario de consultas en el evento loadDim 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>"

Page 47: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO

POR SU ATENCIÓN GRACIAS.