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 PresentationTRANSCRIPT
![Page 1: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/1.jpg)
ADO.NET
MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO
![Page 2: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/2.jpg)
DIRIGIDO A:
Este manual esta dirigido a
![Page 3: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/3.jpg)
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](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/4.jpg)
Nombres de las cajas de Texto, botones y etiqueta
TxtclaveTxtnombreTxtinversionTxtfechabtnAgregarbtnGuardarbtnImprimirbtnEliminarbtnSaliretposicion
![Page 5: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/5.jpg)
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](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/6.jpg)
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](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/7.jpg)
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](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/8.jpg)
Agregamos los siguientes campos, nombre, fecha e inversión:
![Page 9: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/9.jpg)
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](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/10.jpg)
Guardamos nuestra tabla y le ponemos el nombre de Datos.
![Page 11: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/11.jpg)
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](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/12.jpg)
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](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/13.jpg)
Seleccionar los siguientes controles para agregarlos:
![Page 14: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/14.jpg)
Ahora agregamos un OleDbDataAdapter a nuestro formulario y seleccionamos New Connection.
![Page 15: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/15.jpg)
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](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/16.jpg)
Seleccionamos Microsoft Acces Database
![Page 17: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/17.jpg)
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](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/18.jpg)
Al tener nuestra conexión damos clic en siguiente:
![Page 19: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/19.jpg)
Seleccionamos use sql statements y damos clic en siguiente:
![Page 20: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/20.jpg)
Damos clic en QueryBuilder
![Page 21: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/21.jpg)
Aquí agregamos la tabla Datos.
![Page 22: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/22.jpg)
Seleccionamos todas las columnas damos clic en Ok:
![Page 23: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/23.jpg)
Nos queda la consulta de la siguiente manera y damos clic en Siguiente:
![Page 24: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/24.jpg)
Damos clic en finalizar
![Page 25: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/25.jpg)
Luego generamos un Dataset y damos clic en ok.
![Page 26: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/26.jpg)
Debemos de tener en la parte inferior nuestro Oledbdataadapter, Oledbconnection y dataset11
![Page 27: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/27.jpg)
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](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/28.jpg)
Cambiar el nombre a Dataset11 por DsObras y al OleDbDataAdapter por DaObras
![Page 29: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/29.jpg)
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](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/30.jpg)
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](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/31.jpg)
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](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/32.jpg)
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](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/33.jpg)
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](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/34.jpg)
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](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/35.jpg)
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](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/36.jpg)
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](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/37.jpg)
Para imprimir a excel debemos de agregar una referencia de la siguiente manera:
![Page 38: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/38.jpg)
Agregar las referencias que se encuentran en la carpeta obras.
![Page 39: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/39.jpg)
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](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/40.jpg)
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](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/41.jpg)
CONSULTAS: Agregue y diseñe el siguiente formulario.
![Page 42: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/42.jpg)
Nombres de los controles del formulario consultas:
cboNombres
rbtNombresa
rbtNombresd cmdSort
gridobras
cmdNames
![Page 43: MANUAL PARA CREAR BASES DE DATOS EN VISUAL STUDIO](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/43.jpg)
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](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/44.jpg)
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](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/45.jpg)
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](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/46.jpg)
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](https://reader036.vdocuments.mx/reader036/viewer/2022081420/568165c0550346895dd8c25c/html5/thumbnails/47.jpg)
POR SU ATENCIÓN GRACIAS.