Sunteți pe pagina 1din 37

PRCTICA A

REALIZAR EN EL
CURSO DE ADO.NET
SISTEMA AGENDA.NET

Crear un nuevo proyecto

DISEAR 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

Cdigo 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 CONSTRUCCIN")
Case 2
MsgBox("EN CONSTRUCCIN")
Case 3
End
End Select

End Sub

Cdigo 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

Disear el formulario de altas

Nombres de los controles

txtNombre
txtTelefono
txtMail
txtCumple
btnPrimero
btnAnterior
btnSiguiente
btnUltimo

btnAgregar
btnGuardar
btnBorrar
btnImprimir
btnSalir
Datagrid1

Crear la conexin a la base de datos y


seleccionar el proveedor de datos

Seleccionar la base de datos y


probar la conexin

Conexin 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:

Cdigo 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

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

Cdigo mostrar posicin


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 'nmero (1, 2, ...) de registro
'Mostrar informacin en la etiqueta
lblRegistros.Text = iPos.ToString & " de " & iTotal.ToString
End If
End Sub

Ahora si podemos desplazarnos a los diferentes registros a


travs de los botones programados.

Cdigo para el botn 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

Cdigo para el bton 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

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

Agregar una referencia a Excel


para exportar los datos.

Cdigo 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 = "CUMPLEAOS"
.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 disee el siguiente formulario.

Nombres de los controles del


formulario consultas:
cmdNames

rbtNombresA
rbtNombresD

cboNombres

cmdSort

gridAmigos

CONSULTAS
Agregar el siguiente cdigo en la parte superior para importar las clases de la base de
datos OleDb.

Imports System.Data.OleDb
Crear una conexin 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)

Cdigo para realizar consultas


en el botn 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)
End If

Cdigo para el botn 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"
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
DVAmigos.Sort = strSort
'Display the view in the datagrid
Me.gridAmigos.DataSource = DVAmigos

Cdigo 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

Disear el siguiente formulario: El control CrystalReportViewver debe de llamarse crv. Y


debemos importar lo siguiente: Imports CrystalDecisions.CrystalReports.Engine

Cdigo para los reportes,


botn 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

S-ar putea să vă placă și