Download - Ejemplo de Acceso a Datos Con Una Base de Access

Transcript
Page 1: Ejemplo de Acceso a Datos Con Una Base de Access

Ejemplo de acceso a datos con una base de Access

Publicado: 13/Jun/2002Actualizado: 19/Abr/2003

En este ejemplo veremos cómo acceder a una base de datos de Access, usando los objetos del espacio de nombres OLEDB.Los conceptos que se tratarán serán los siguientes:- Crear una conexión a la base de datos.- Mostrar las tablas de la base de datos indicada.- Mostrar las columnas (o campos) de una tabla.- Crear un DataAdapter para acceder a los datos devueltos por una consulta.- Crear un DataSet basado en los datos asociados al DataAdapter.- Crear nuevos registros.- Modificar registros.- Eliminar registros.- Mostrar el contenido de la tabla en un control ListView.

  

Nota del 20/Jul/2002:He recibido varios mensajes diciendo que les daba error el ejemplo aquí puesto, he probado y efectivamente, me da error... le he puesto una captura (en el método Conecta) y me muestra un error de que la cadena SQL no es válida, pero si continuo, funciona bien.Aunque, he de aclarar que ese error se produce en el código del ejemplo adjunto, si se deja el texto que por defecto tiene la caja de textos en la que se indica la cadena SQL, si se deja en blanco, no se produce error.He modificado el código aquí mostrado, el cual puedes ver pulsando este link.

Nota del 06/Ene/2006:Si este ejemplo te parece muy complicado, puedes ver otro más simple.

Los objetos a usar en el proyecto.Los objetos que vamos a usar en este ejemplo, en su gran mayoría residen en el espacio de nombres System.Data.OleDb, aunque también se usarán objetos genéricos (DataSet, DataRow, DataColumn) que residen en System.Data.Para que nos sea más fácil declarar esos objetos, importaremos el espacio de nombres System.Data.OleDb y dado que usaremos procedimientos genéricos, estos los incluiremos en un módulo, al que llamaremos: ADONETUtil, veamos el código con las declaraciones de los objetos que usaremos en el proyecto:

Page 2: Ejemplo de Acceso a Datos Con Una Base de Access

'------------------------------------------------------------------------------

' Prueba de acceso a base de tipo Access con ADO.NET (25/May/02)

' Módulo con las declaraciones de objetos

'

' ©Guillermo 'guille' Som, 2002

'------------------------------------------------------------------------------

Imports System.Data.OleDb

Module ADONETUtil

Friend dbConnection As OleDbConnection

'

Friend dbDataTable As Data.DataTable

Friend dbDataSet As Data.DataSet

Friend dbDataAdapter As OleDbDataAdapter

'

Friend CadenaConexion As String

Friend CadenaSelect As String

'

Friend ArchivoDatos As String

Friend NombreTabla As String = "Tabla1"

'

La variable CadenaConexion será la cadena con la que conectaremos a la base de datos.La variable CadenaSelect será el código SQL que usaremos para acceder a la tabla de esa base de datos.La variable ArchivoDatos será el nombre completo de la base de datos (Path incluido).La variable NombreTabla será el nombre que usaremos para identificar a los datos que cargaremos en el objeto DataAdapter, ese nombre no tiene nada que ver con el nombre de la tabla a la que vamos a acceder, es sólo un nombre que usaremos con los distintos objetos de ADO.NET.

 

Conectar a una base de datos del tipo AccessPara conectar a la base de datos y crear los objetos que cargarán la tabla (definida en la consulta SQL contenida en la variable CadenaSelect), vamos a crear un procedimiento en el mismo módulo ADONETUtil:

Page 3: Ejemplo de Acceso a Datos Con Una Base de Access

Friend Sub Conectar(Optional ByVal nombreBaseDatos As String = "", _

Optional ByVal commandString As String = "")

If nombreBaseDatos = "" Then

nombreBaseDatos = ArchivoDatos

End If

ArchivoDatos = nombreBaseDatos

If ArchivoDatos = "" Then

Exit Sub

End If

'

If CadenaSelect = "" Then

CadenaSelect = "SELECT * FROM Table1"

End If

If commandString = "" Then

commandString = CadenaSelect

End If

CadenaSelect = commandString

'

CadenaConexion = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & ArchivoDatos

'

Try

dbConnection = New OleDbConnection(CadenaConexion)

Catch e As Exception

MessageBox.Show("Error al crear la conexión:" & vbCrLf & e.Message)

Exit Sub

End Try

'

dbConnection.Open()

'

dbDataSet = New Data.DataSet()

'

dbDataAdapter = New OleDbDataAdapter(CadenaSelect, dbConnection)

'

Page 4: Ejemplo de Acceso a Datos Con Una Base de Access

Dim commandBuilder As New OleDbCommandBuilder(dbDataAdapter)

'

dbDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey

'dbDataAdapter.Fill(dbDataSet, NombreTabla)

' Cambio para comprobar que funciona, (20/Jul/02)

' En la versión Architect me da error, pero continua funcionando.

' Aunque el error lo da si se pasa una cadena SQL que no es correcta,

' por ejemplo, cuando se inicia la aplicación y se deja el texto por defecto.

Try

dbDataAdapter.Fill(dbDataSet, NombreTabla)

Catch ex As Exception

MessageBox.Show("Error en Fill:" & vbCrLf & ex.Message)

End Try

'

End Sub

A este procedimiento se le pueden indicar dos parámetros:El primero indicará el nombre de la base de datos (path incluido), mientras que el segundo será la instrucción SQL que nos permitirá acceder a la tabla. Cuando veamos el código del formulario, tendremos ocasión de ver cómo se llama a este procedimiento.

Lo que aquí tenemos que destacar es lo siguiente:La cadena de conexión que tenemos que usar para conectar con la base de datos es igual que la usada en las versiones anteriores de ADO, en esto no ha cambiado nada; se le indica el tipo de proveedor y el nombre de la base de datos.Creamos un nuevo objeto del tipo DataSet, que será el que nos permita acceder a los datos.Creamos un objeto del tipo DataAdapter, este será el que realmente nos permita acceder a los datos físicos de la base de datos, primero para rellenar el DataSet y posteriormente para actualizar los cambios realizados en la base de datos.Es importante saber que los datos contenidos en el objeto DataSet están en memoria y se acceden y manipulan de forma independiente, sin ninguna relación directa con la base de datos original. Para que los cambios realizados en memoria se puedan reflejar de forma permanente en la base de datos, tenemos que usar el objeto DataAdapter.Una vez creado el DataAdapter, al que se le indica la cadena de selección y la cadena de conexión o el objeto del tipo Connection. En este caso, le he indicado el objetoConnection, pero si no queremos crear una conexión permanente, también podemos usar la misma cadena de conexión usada para crear el objeto Connection en lugar de ese objeto.Para poder realizar cambios en la base de datos, hay que indicarle

Page 5: Ejemplo de Acceso a Datos Con Una Base de Access

al DataAdapter los comandos SQL que habría que usar para añadir, modificar y eliminar, pero esos comandos se pueden crear de forma automática creando un nuevo objeto del tipo CommandBuilder, al que se le pasará como parámetro el adaptador que usará dichos comandos, en realidad el objeto CommandBuilder no se usa nada más que para que de esta forma se asignen dichos comandos de actualización de datos.Si la tabla a la que queremos acceder tiene clave principal (cosa que es común o debería serlo en todas las tablas), le indicamos mediante la asignación a la propiedadMissingSchemaAction el valor de añadir con clave. Si no hacemos esta asignación y la tabla tiene un campo que se incrementa automáticamente, no podríamos crear varios registros (o filas) en memoria y después actualizar esas nuevas filas de forma permanente, ya que nos daría un error de que hay duplicidad en el campo (o columna) autoincremental.Por último, llenamos el objeto DataSet con los datos del DataAdapter, el segundo parámetro es el nombre que le vamos a dar a la tabla virtual (la que se crea en memoria), si no le damos un nombre a esa tabla virtual del DataSet, se asignará de forma predeterminada con el nombre Table. Es conveniente asignar un nombre, ya que un objetoDataSet permite tener en memoria distintos datos, de la misma o de otras tablas o consultas. Ese nombre será el que usaremos para acceder a esos datos en memoria, ya que todos los accesos al contenido del DataSet, como he comentado antes, se realizan de forma desconectada, es decir sin relación ninguna con la base de datos física.

 

Los nombres de las tablas de una base de datosVamos a crear una función que devuelva una matriz (o array) del tipo String, con los nombres de las tablas de la base de datos.

Friend Function NombresTablas() As String()

Dim nomTablas() As String

Dim dataTable As Data.DataTable

Dim dbNull As System.DBNull

Dim restrictions() As Object = {dbNull, dbNull, dbNull, "TABLE"}

Dim i As Integer

'

If dbConnection Is Nothing Then

dbConnection = New Data.OleDb.OleDbConnection(CadenaConexion)

End If

If dbConnection.State <> ConnectionState.Open Then

dbConnection.Open()

End If

'

Page 6: Ejemplo de Acceso a Datos Con Una Base de Access

dataTable = dbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, restrictions)

i = dataTable.Rows.Count - 1

If i > -1 Then

ReDim nomTablas(i)

For i = 0 To dataTable.Rows.Count - 1

nomTablas(i) = dataTable.Rows(i).Item("TABLE_NAME").ToString()

Next

End If

'

Return nomTablas

End Function

Antes de llamar a esta función tendremos que tener asignada la cadena de conexión o, mejor aún, creada la conexión a la base de datos. Eso es lo que se hace en las primeras líneas, si el objeto del tipo Connection no está creado, se crea un nuevo objeto, usando la cadena de conexión. En caso de que esté creado el objeto, se comprueba si está abierta dicha conexión, de no ser así, se abre.A continuación asignamos un objeto del tipo DataTable con el "esquema" de las tablas contenidas en la base de datos a la que apunta el objeto Connection. El "truco" para conseguir los nombres de las tablas, está en el array restrictions, particularmente en el cuarto elemento: "TABLE".Recorremos el contenido del objeto DataTable y accedemos a cada una de las filas cuyo elemento contenga la cadena "TABLE_NAME", el cual nos dará el nombre de cada una de las tablas. Ese nombre lo asignamos a cada uno de los elementos del array que estamos usando de forma interna, el cual será el que la función devuelva.

 

Los nombres de los campos (o columnas) de una tablaPara saber los nombres de los campos o columnas de una tabla, usaremos el contenido del objeto DataSet que hace referencia a la tabla que hemos cargado mediante elDataAdapter, aunque también podría servirnos para acceder a cualquier tabla virtual contenida en el DataSet.También vamos a crear una función que devuelva una matriz del tipo String:

Friend Function NombresColumnas() As String()

Dim columna As Data.DataColumn

Dim i, j As Integer

Page 7: Ejemplo de Acceso a Datos Con Una Base de Access

Dim nomCol() As String

'

j = dbDataSet.Tables(NombreTabla).Columns.Count - 1

ReDim nomCol(j)

For i = 0 To j

columna = dbDataSet.Tables(NombreTabla).Columns(i)

nomCol(i) = columna.ColumnName

Next

Return nomCol

End Function

Creo que el código es bastante auto-explicativo y no necesita más aclaración.

 

Asignar la cabecera de un control ListView con los nombres de las columnas o campos de una tablaPara terminar con el código del módulo ADONETUtil, vamos a ver unos métodos que usaremos para asignar las columnas (o cabecera) de un ListView con los nombres de las columnas o campos de la tabla que vamos a utilizar.El método se llama AsignarCabeceraLista y tendrá dos implementaciones, una indicando sólo el nombre del ListView y la otra en la que además se indicará un controlComboBox en el cual se asignarán también esos nombres de las columnas de la tabla.

Friend Sub AsignarCabeceraLista(ByVal ListView1 As ListView)

Dim columna As Data.DataColumn

Dim i, j As Integer

'

With ListView1

.View = View.Details

.FullRowSelect = True

.GridLines = True

.LabelEdit = False

.HideSelection = False

.Columns.Clear()

End With

Page 8: Ejemplo de Acceso a Datos Con Una Base de Access

'

Dim lasColumnas() As String

lasColumnas = NombresColumnas()

'

If Not lasColumnas Is Nothing Then

For i = 0 To lasColumnas.Length - 1

ListView1.Columns.Add(lasColumnas(i), 100, HorizontalAlignment.Left)

Next

End If

'

End Sub

Friend Sub AsignarCabeceraLista(ByVal ListView1 As ListView, _

ByVal cboCampos As ComboBox)

Dim i As Integer

'

AsignarCabeceraLista(ListView1)

cboCampos.Items.Clear()

For i = 0 To ListView1.Columns.Count - 1

cboCampos.Items.Add(ListView1.Columns(i).Text)

Next

'

If cboCampos.Items.Count > 0 Then

cboCampos.SelectedIndex = 0

End If

End Sub

Creo que tampoco necesita explicación, ya que lo único que se hace es llamar a la función NombresColumnas y el contenido de ese array es el que se asigna a la cabecera del ListView que se ha indicado en el parámetro.En cuanto a la segunda implementación, se asigna al control ComboBox pasado como parámetro esos mismos nombres.Cuando veamos el código de los formularios, sabremos cuando usar una u otra versión de este método.

 

Llenar un ListView con el contenido de una tabla

Page 9: Ejemplo de Acceso a Datos Con Una Base de Access

El siguiente método del módulo ADONETUtil rellenará un control ListView con los datos de la tabla cargada en el objeto DataSet.

Friend Sub LLenarLista(ByVal unListView As ListView)

Dim i As Integer

Dim lwItem As ListViewItem

Dim fila As Data.DataRow

'

unListView.Items.Clear()

'

For Each fila In dbDataSet.Tables(NombreTabla).Rows

For i = 0 To unListView.Columns.Count - 1

If i = 0 Then

lwItem = unListView.Items.Add(fila(i).ToString)

lwItem.Tag = fila

Else

lwItem.SubItems.Add(fila(i).ToString)

End If

Next

Next

End Sub

El código es también bastante simple, sólo quiero aclarar un detalle: La asignación del objeto fila al TAG del elemento del ListView.Realmente no es necesario, pero yo lo utilizo esa fila para acceder a cada uno de los registros de la tabla, ya que al modificar los datos, sólo los reflejaremos en el contenido del ListView y de esa forma sabremos a que fila estamos accediendo. Cuando actualicemos los datos, usaremos el objeto que hemos guardado en la propiedad Tag del objetoListViewItem, y ese mismo objeto será el que usaremos para eliminar una fila del DataSet.

 

Para terminar con el código del módulo, una función que usaremos para mostrar información de la base de datos a la que estamos accediendo. En este caso es una función que recibe como parámetro un path completo y devuelve sólo el nombre de la base de datos:

Friend Function NombreBase(ByVal path As String) As String

Page 10: Ejemplo de Acceso a Datos Con Una Base de Access

' Devolver sólo el nombre de la base de datos

Dim i As Integer

'

i = path.LastIndexOf("\")

If i > -1 Then

Return path.Substring(i + 1)

End If

End Function

Aquí se podrían haber usado funciones "clásicas" de Visual Basic, como InStr o Mid, pero he preferido usar sus equivalentes de VB.NET, entre otras cosas porque forman parte del objeto String. En el caso de LastIndexOf, busca la última ocurrencia de la cadena indicada en el parámetro, si dicha cadena no forma parte del objeto, (en este caso la variable path), se devuelve un valor -1 y en caso de que si esté, se devuelve la posición, pero hay que tener en cuenta que la primera posición está representada por el valor cero.

 

El formulario principalEste es el aspecto del formulario principal (Form1) en tiempo de diseño:

El formulario principal en tiempo de diseño

Este formulario permitirá que se arrastre una base de datos y ese nombre se asignará a la caja de textos del nombre de la base de datos. Los controles tienen asignados los valores de la propiedad Anchor para que se ajusten al tamaño que el usuario quiera darle al formulario, esos detalles podremos verlo en el código completo, ya que aquí sólo mostraré la parte que realmente interesa, es decir lo que está relacionado con el acceso a la base de datos.

Page 11: Ejemplo de Acceso a Datos Con Una Base de Access

Empecemos por el código del botón "Mostrar tablas" y el evento producido cuando se selecciona una tabla del ComboBox:

Private Sub btnAbrirBase_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) _

Handles btnAbrirBase.Click

'

Conectar(txtNombreBase.Text, txtSelect.Text)

'

'

Dim nomTablas() As String

Dim i As Integer

'

nomTablas = NombresTablas()

cboTablas.Items.Clear()

If Not nomTablas Is Nothing Then

For i = 0 To nomTablas.Length - 1

cboTablas.Items.Add(nomTablas(i))

Next

End If

If cboTablas.Items.Count > 0 Then

cboTablas.SelectedIndex = 0

End If

End Sub

Private Sub cboTablas_SelectedIndexChanged(ByVal sender As System.Object, _

ByVal e As System.EventArgs) _

Handles cboTablas.SelectedIndexChanged

txtSelect.Text = "SELECT * FROM " & cboTablas.Text

'

'' Si se quieren mostrar individualmente los nombres de los campos

'Dim lasColumnas() As String

'Dim s As String, i As Integer

''

Page 12: Ejemplo de Acceso a Datos Con Una Base de Access

'CadenaSelect = txtSelect.Text

'lasColumnas = NombresColumnas()

'For i = 0 To lasColumnas.Length - 1

' s &= lasColumnas(i) & ", "

'Next

'' Quitar la última coma

'i = s.LastIndexOf(", ")

's = s.Substring(0, i)

's = "SELECT " & s & " FROM " & cboTablas.Text

'txtSelect.Text = s

End Sub

El primer procedimiento intercepta la pulsación en el botón y asigna los nombres de las tablas en el combo.El segundo, simplemente crea la cadena SQL que se usará para acceder a dicha tabla.El código que está comentado sirve para mostrar los nombres de los campos o columnas de forma individual.

Cuando pulsamos en el botón "Mostrar", se muestra el contenido de la tabla indicada, información que se obtiene del DataSet que contiene los datos en memoria. Aunque, el código mostrado, realmente refresca esa información, esto lo he hecho así para que al volver de modificar los datos, se pueda comprobar que los datos realmente se han guardado en la base de datos.

Private Sub btnMostrar_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) _

Handles btnMostrar.Click

'

With ListView1

.View = View.Details

.FullRowSelect = True

.GridLines = True

.LabelEdit = False

.HideSelection = False

.Columns.Clear()

End With

'

Page 13: Ejemplo de Acceso a Datos Con Una Base de Access

' Volver a reconectar para actualizar los datos desde la base

If Not dbConnection Is Nothing Then

dbConnection.Close()

End If

Conectar(txtNombreBase.Text, txtSelect.Text)

'

AsignarCabeceraLista(ListView1)

LLenarLista(ListView1)

End Sub

Como podemos comprobar, aquí se llaman a los métodos del módulo ADONETUtil, por tanto al principio del código del formulario debemos hacer la importación del espacio de nombres de ese módulo para no tener que especificarlo cada vez que queramos acceder a cualquiera de los procedimientos o variables en el declarado:

' Importamos el módulo con las declaraciones de los objetos a usar

Imports ADONET1.ADONETUtil

ADONET1 es el nombre del "espacio de nombres" (Namespace) de este proyecto.

Para acabar con el código de este formulario, veamos los eventos que se producen al cargarse el formulario (Load) y al cerrarse (Closing), además del evento producido al pulsar en el botón "Mostrar", el cual mostrará el formulario en el que se editan los datos de la tabla indicada.

Private Sub Form1_Load(ByVal sender As Object, _

ByVal e As System.EventArgs) _

Handles MyBase.Load

Me.txtNombreBase.Text = "E:\gsCodigo\Vb6\Pruebas\Bases\db2000NET.mdb"

'

ArchivoDatos = txtNombreBase.Text

CadenaConexion = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & ArchivoDatos

'

With ListView1

.View = View.Details

.FullRowSelect = True

Page 14: Ejemplo de Acceso a Datos Con Una Base de Access

.GridLines = True

.LabelEdit = False

End With

'

cboTablas.Text = ""

End Sub

Private Sub Form1_Closing(ByVal sender As Object, _

ByVal e As System.ComponentModel.CancelEventArgs) _

Handles MyBase.Closing

' Cerrar la conexión

Try

If dbConnection.State = ConnectionState.Open Then

dbConnection.Close()

End If

Catch

End Try

End Sub

Private Sub btnModificar_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) _

Handles btnModificar.Click

Dim f2 As New Form2()

With f2

.DataSource = txtNombreBase.Text

.CommandString = txtSelect.Text

.ShowDialog()

End With

btnMostrar_Click(btnMostrar, e)

End Sub

En el evento Load, asignamos los valores iniciales, en el evento Closing, comprobamos si tenemos la conexión abierta y de ser así la cerramos, debido a que puede ser que se cierre el formulario sin necesidad de haber creado dicho objeto, interceptamos el error que se pudiera producir.Por otro lado, cuando pulsamos en el botón Modificar, creamos una nueva instancia del formulario en el que modificaremos la información y asignamos los valores de la base de datos y la cadena SQL que usaremos

Page 15: Ejemplo de Acceso a Datos Con Una Base de Access

para conectar, esto lo hago así por si se pulsa en dicho botón sin haber creado la conexión.

El formulario de edición de datosPara terminar con este ejemplo de acceso a datos usando ADO.NET, veamos el formulario que usaremos para modificar la información de la base de datos.

El aspecto del formulario (FORM2) será el mostrado en la siguiente imagen:

El formulario de introducción de datos

En este formulario, los controles también están "anclados" para que se adapten al tamaño que el usuario quiera darle al formulario.

Empecemos por las variables o propiedades que este formulario expone al mundo externo:

' Importamos el módulo con las declaraciones de los objetos a usar

Imports ADONET1.ADONETUtil

Public Class Form2

Inherits System.Windows.Forms.Form

Friend DataSource As String

Friend CommandString As String

'

Private lwItemActual As ListViewItem

Page 16: Ejemplo de Acceso a Datos Con Una Base de Access

También usamos el Imports para poder usar los procedimientos del módulo ADONETUtil y declaramos dos propiedades: DataSource y CommandString, las cuales usaremos para acceder a la base de datos.La variable lwItemActual hará referencia al elemento del ListView que esté actualmente seleccionado.

En el evento Load del formulario, se asignarán algunos valores por defecto y se mostrará el contenido de la tabla indicada en el ListView:

Private Sub Form2_Load(ByVal sender As System.Object, _

ByVal e As System.EventArgs) _

Handles MyBase.Load

Me.txtCampo1.Text = ""

'

' para usar este formulario como formulario inicial

If DataSource = "" Then

DataSource = "E:\gsCodigo\Vb6\Pruebas\Bases\db2000NET.mdb"

End If

If CommandString = "" Then

CommandString = "SELECT * FROM Table1"

End If

'

lblInfo.Text = "Base: " & NombreBase(DataSource) & ", Select: " & CommandString

'

If dbConnection Is Nothing Then

Conectar(DataSource, CommandString)

End If

'

AsignarCabeceraLista(ListView1, cboCampos)

LLenarLista(ListView1)

'

Me.AcceptButton = btnAsignar

End Sub

Cuando seleccionamos un nuevo elemento del ListView, se asigna la variable que contiene el elemento actual y se muestra la información o datos de dicha fila.

Page 17: Ejemplo de Acceso a Datos Con Una Base de Access

Private Sub ListView1_SelectedIndexChanged(ByVal sender As Object, _

ByVal e As System.EventArgs) _

Handles ListView1.SelectedIndexChanged

Try

lwItemActual = ListView1.SelectedItems(0)

Catch

End Try

End Sub

Private Sub ListView1_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) _

Handles ListView1.Click, cboCampos.SelectedIndexChanged

Try

lwItemActual = ListView1.SelectedItems(0)

MostrarCampo()

Catch

End Try

End Sub

Como podemos comprobar, el procedimiento ListView1_Click realmente intercepta dos eventos, el evento Click del ListView y el evento SelectedIndexChanged del Combo, de forma que se muestre la información del campo seleccionado en el ComboBox. De eso se encarga el procedimiento MostrarCampo:

Private Sub MostrarCampo()

Dim i As Integer

'

Try

i = cboCampos.SelectedIndex

If i = 0 Then

txtCampo1.Text = lwItemActual.Text

ElseIf i > -1 Then

txtCampo1.Text = lwItemActual.SubItems(i).Text

End If

Page 18: Ejemplo de Acceso a Datos Con Una Base de Access

Catch

End Try

End Sub

Este procedimiento simplemente muestra el contenido del campo que está seleccionado en el control ComboBox.

 

Asignar los datosCuando pulsamos en el botón Asignar, el cual hemos asignado como botón "Aceptar" del formulario, es decir el que tomará el foco cuando pulsemos la tecla Intro, se asignarán los cambios realizados al campo (o columna) que estamos editando:

Private Sub AsignarCampo(ByVal sender As System.Object, _

ByVal e As System.EventArgs) _

Handles btnAsignar.Click

' Asignar al ListView el campo modificado

Dim i As Integer

'

i = cboCampos.SelectedIndex

If i = 0 Then

lwItemActual.Text = txtCampo1.Text

ElseIf i > -1 Then

lwItemActual.SubItems(i).Text = txtCampo1.Text

End If

End Sub

 

Eliminar una filaCuando pulsamos en el botón Eliminar, borramos la fila seleccionada del ListView y también esa misma fila del DataSet, y como comenté anteriormente, en la propiedad Tagdel elemento del ListView tenemos una referencia a la fila de datos, por tanto usamos ese objeto para eliminar la fila de la colección Rows del objeto DataSet, ya que el método Remove de la colección Rows acepta como parámetro un objeto del tipo DataRow:

Page 19: Ejemplo de Acceso a Datos Con Una Base de Access

Private Sub btnEliminar_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) _

Handles btnEliminar.Click

' Eliminar la fila indicada

Dim fila As Data.DataRow

'

fila = CType(ListView1.SelectedItems(0).Tag, Data.DataRow)

dbDataSet.Tables(NombreTabla).Rows.Remove(fila)

ListView1.Items.Remove(ListView1.SelectedItems(0))

End Sub

 

Crear una nueva fila (o registro)Para crear un nuevo registro (o fila), tendremos que asignar unos valores nulos o por defecto a una nueva fila creada en la memoria, después esa fila la añadiremos a la tabla que mantenemos en el DataSet.Debido a que algunos campos no permiten valores nulos, tendremos que tener ese detalle en cuenta y de ser así, asignaremos un valor adecuado al tipo de datos de cada una de las columnas (o campos) del registro que hemos creado, esto lo conseguimos comprobando el tipo de datos de cada una de las columnas de la nueva fila. Hay que tener en cuenta que los tipos de datos se guardan usando el que se define en .NET Framework, no los tipos que utiliza Visual Basic, por tanto, para saber si el tipo de una columna es del tipo Integer, tendremos que usar System.Int32, de todas formas, para saber el tipo de dato, (que lo da la propiedad DataType del objeto DataColumn), he utilizado la conversión a cadena generada por ToString, por lo que dicho tipo se convierte en el formato "System.Tipo", veamos el código para aclarar todo este lío:

Private Sub btnNuevo_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) _

Handles btnNuevo.Click

' Añadir una nueva fila (o registro)

Dim fila As Data.DataRow

Dim i As Integer

Dim lwItem As ListViewItem

Page 20: Ejemplo de Acceso a Datos Con Una Base de Access

Dim columna As Data.DataColumn

'

fila = dbDataSet.Tables(NombreTabla).NewRow

fila.BeginEdit()

For i = 0 To dbDataSet.Tables(NombreTabla).Columns.Count - 1

columna = dbDataSet.Tables(NombreTabla).Columns(i)

'Debug.WriteLine(columna.DataType.ToString)

If columna.AutoIncrement = False Then

Select Case columna.DataType.ToString

Case "System.String"

fila(i) = columna.ColumnName

Case "System.Boolean"

fila(i) = False

Case "System.Byte", "System.SByte"

fila(i) = CByte(0)

Case "System.Char"

fila(i) = " "c

Case "System.DateTime", "System.TimeSpam"

fila(i) = Now

Case "System.Decimal", "System.Double", "System.Single"

fila(i) = 0

Case Else

'Case "System.Int32","System.UInt32"

' fila(i) = 0

If columna.DataType.ToString.IndexOf("System.Int") > -1 Then

fila(i) = 0

ElseIf columna.DataType.ToString.IndexOf("System.UInt") > -1 Then

fila(i) = 0

End If

End Select

End If

Next

fila.EndEdit()

Page 21: Ejemplo de Acceso a Datos Con Una Base de Access

' Añadir la fila a la tabla

dbDataSet.Tables(NombreTabla).Rows.Add(fila)

'

' Mostrar la nueva fila en el ListView

For i = 0 To ListView1.Columns.Count - 1

If i = 0 Then

lwItem = ListView1.Items.Add(fila(i).ToString)

lwItem.Tag = fila

Else

lwItem.SubItems.Add(fila(i).ToString)

End If

Next

'

End Sub

Lo que en este evento hacemos es crear una nueva fila mediante el método NewRow, asignamos los campos (o columnas) de dicha fila y la añadimos a la colección Rows de la tabla. Hay que tener en cuenta que al crear una nueva fila con NewRow no se añade a la colección de filas (o registros), simplemente se devuelve un objeto que está preparado para que se le asignen los datos correspondientes. Antes de asignar cada una de las columnas, comprobamos si dicha columna está marcada como autoincremental, de ser así, no asignamos nada, ya que es el propio DataAdapter el que se encarga de asignar el valor de dicha columna.

En este punto quiero hacer una aclaración, debido a que los datos los estamos asignando a un objeto que mantiene la información en la memoria, si existen varias aplicaciones que acceden a la misma base de datos y cada una de ellas crea nuevas filas, el valor asignado al campo (o columna) AutoIncrement puede que no sea el que definitivamente tenga en la base de datos. Por tanto, debemos tener esto presente si el valor asignado a esa columna lo utilizamos para otros menesteres.

Una vez que hemos añadido la nueva fila a la tabla, asignamos el contenido de la misma al ListView y también asignamos a la propiedad Tag una referencia a dicha fila.

 

Guardar la información en la base de datosPor último vamos a ver cómo pasar la información mantenida en la memoria a la base de datos, con idea de que los cambios realizados se queden guardados permanentemente.Esto lo hacemos cuando el usuario pulsa en el botón de "Actualizar Base" y el código usado es el siguiente:

Page 22: Ejemplo de Acceso a Datos Con Una Base de Access

Private Sub btnActualizarBase_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) _

Handles btnActualizarBase.Click

' Actualizar la base de datos con los cambios realizados

Dim fila As Data.DataRow

Dim i, j As Integer

Dim lwItem As ListViewItem

Dim columna As Data.DataColumn

'

lblInfo.Tag = lblInfo.Text

lblInfo.Text = "Actualizando los datos..."

lblInfo.Refresh()

Try

For i = 0 To ListView1.Items.Count - 1

lwItem = ListView1.Items(i)

fila = CType(ListView1.Items(i).Tag, Data.DataRow)

fila.BeginEdit()

j = 0

For Each columna In dbDataSet.Tables(NombreTabla).Columns

If j = 0 Then

If columna.AutoIncrement = False Then

fila(j) = lwItem.Text

End If

Else

If columna.AutoIncrement = False Then

fila(columna.ColumnName) = lwItem.SubItems(j).Text

End If

End If

'

j += 1

Next

fila.EndEdit()

Page 23: Ejemplo de Acceso a Datos Con Una Base de Access

Next

'

'

dbDataAdapter.Update(dbDataSet, NombreTabla)

dbDataSet.AcceptChanges()

'

'

lblInfo.Text = CStr(lblInfo.Tag)

Catch errActualizar As Exception

lblInfo.Text = errActualizar.Message

MsgBox(errActualizar.Message)

End Try

End Sub

En este procedimiento actualizamos la información de cada una de las filas, para ello usamos el objeto almacenado en la propiedad Tag de cada uno de los elementos delListView que como recordarás era en realidad una referencia a cada una de las filas de la tabla, (realmente un objeto del tipo DataRow). Recorremos cada una de las columnas y asignamos sólo los datos si no es una columna del tipo AutoIncrement.La llamada a los métodos BeginEdit y EndEdit de cada fila es para que no se produzcan los eventos asociados a un objeto de este tipo, no son realmente necesarios para poder cambiar los contenidos de las columnas.

Una vez que hemos asignado todos los datos del ListView, llamamos al método Update del DataAdapter, este método es el que realmente hace que los datos se guarden físicamente en la base de datos.Después llamamos al método AcceptChanges del objeto DataSet para que "sepa" que hemos aceptado la nueva información y marque la información de forma que sean iguales a los datos que tiene la base de datos real.

Y esto es todo... que no es poco... en otras ocasiones veremos cómo acceder a los datos de una base de datos mediante controles enlazados y con un DataGrid que es en realidad la forma más fácil de hacerlo.Realmente si hubiésemos usado ese control, no tendríamos que haber escrito la mayoría del código que he mostrado, pero como se que hay gente que le gusta tener un control "casi" total sobre cómo se accede a la información... pues eso, que aquí está la forma "difícil" de hacerlo y ya habrá ocasión de ver la forma "fácil".

En otra ocasión, veremos este mismo código aplicado a una base de datos de SQL Server.

Nota 19/Abr/2003:Esa ocasión ya ha llegado, sigue este link para el ejemplo de SQL Server.

Nos vemos.Guillermo

Page 24: Ejemplo de Acceso a Datos Con Una Base de Access

Introducir datos desde un textbox a una base access en vb.net

La idea basica es utilizar un 'bindingsource' y un commandbuilder para tu adataptador de datos, a partir de este concepto es tan simple como añadir un 'datarow' o registro a tu tabla de datos 'datatable' cada vez que pulsamos 'enter' y la longitud de los datos introducidos es mayor de cero. Posteriormente para actualizar o añadir los registros del 'datatable' a la BD de access utilizaremos el mandato 'update' (al pulsar un boton en nuestro caso), o asociado al momento que consideres oportuno.Puedes descargarte este ejemplo haciendo click en 'attachments'Imports System.Data.OleDbImports System.Data.DataRowPublic Class Form1  Private MiConexion As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\bd1.mdb")  Private MiAdaptador As New OleDbDataAdapter("SELECT * FROM Nombres", MiConexion)  Private MiDataSet As New DataSet()  Private MiEnlazador As New BindingSource  Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress    If (e.KeyChar = Chr(Keys.Enter)) And (Me.TextBox1.Text.Length > 0) Then      Dim nombre As DataRow      nombre = MiDataSet.Tables(0).NewRow()      nombre("Nombre") = TextBox1.Text      MiDataSet.Tables(0).Rows.Add(nombre)      Me.TextBox1.Text = ""      Me.ComboBox1.SelectedIndex = Me.ComboBox1.Items.Count - 1    End If  End Sub  Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load    Dim commandbuilder As New OleDb.OleDbCommandBuilder(Me.MiAdaptador)    MiConexion.Open()    MiAdaptador.Fill(MiDataSet)    MiEnlazador.DataSource = MiDataSet.Tables(0)    Me.ComboBox1.DataSource = MiEnlazador    Me.ComboBox1.DisplayMember = "Nombre"    Me.ComboBox1.ValueMember = "Id"    Me.TextBox1.Select()  End Sub   Private Sub Guardar(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click    Me.MiAdaptador.Update(CType(Me.MiEnlazador.DataSource, DataTable))  End Sub

Espero que sea de tu utilidad.Pep Lluis,

Page 25: Ejemplo de Acceso a Datos Con Una Base de Access

Line With Band DemoNOTE: The code on this page is for ZedGraph version 5. You can view the code for version

4 here.

Sample Code in C#

// Call this method from the Form_Load method, passing your ZedGraphControlpublic void CreateChart( ZedGraphControl zgc ){ GraphPane myPane = zgc.GraphPane; // Set the title and axis labels myPane.Title.Text = "Line Graph with Band Demo"; myPane.XAxis.Title.Text = "Sequence"; myPane.YAxis.Title.Text = "Temperature, C"; // Enter some random data values double[] y = { 100, 115, 75, 22, 98, 40, 10 }; double[] y2 = { 90, 100, 95, 35, 80, 35, 35 }; double[] y3 = { 80, 110, 65, 15, 54, 67, 18 }; double[] x = { 100, 200, 300, 400, 500, 600, 700 }; // Fill the axis background with a color gradient

Page 26: Ejemplo de Acceso a Datos Con Una Base de Access

myPane.Chart.Fill = new Fill( Color.FromArgb( 255, 255, 245 ), Color.FromArgb( 255, 255, 190 ), 90F ); // Generate a red curve with "Curve 1" in the legend LineItem myCurve = myPane.AddCurve( "Curve 1", x, y, Color.Red ); // Make the symbols opaque by filling them with white myCurve.Symbol.Fill = new Fill( Color.White ); // Generate a blue curve with "Curve 2" in the legend myCurve = myPane.AddCurve( "Curve 2", x, y2, Color.Blue ); // Make the symbols opaque by filling them with white myCurve.Symbol.Fill = new Fill( Color.White ); // Generate a green curve with "Curve 3" in the legend myCurve = myPane.AddCurve( "Curve 3", x, y3, Color.Green ); // Make the symbols opaque by filling them with white myCurve.Symbol.Fill = new Fill( Color.White ); // Manually set the x axis range myPane.XAxis.Scale.Min = 0; myPane.XAxis.Scale.Max = 800; // Display the Y axis grid lines myPane.YAxis.MajorGrid.IsVisible = true; myPane.YAxis.MinorGrid.IsVisible = true; // Draw a box item to highlight a value range BoxObj box = new BoxObj( 0, 100, 1, 30, Color.Empty, Color.FromArgb( 150, Color.LightGreen ) ); box.Fill = new Fill( Color.White, Color.FromArgb( 200, Color.LightGreen ), 45.0F ); // Use the BehindAxis zorder to draw the highlight beneath the grid lines box.ZOrder = ZOrder.E_BehindCurves; // Make sure that the boxObj does not extend outside the chart rect if the chart is zoomed box.IsClippedToChartRect = true; // Use a hybrid coordinate system so the X axis always covers the full x range // from chart fraction 0.0 to 1.0 box.Location.CoordinateFrame = CoordType.XChartFractionYScale; myPane.GraphObjList.Add( box ); // Add a text item to label the highlighted range TextObj text = new TextObj( "Optimal\nRange", 0.95f, 85, CoordType.AxisXYScale, AlignH.Right, AlignV.Center ); text.FontSpec.Fill.IsVisible = false; text.FontSpec.Border.IsVisible = false; text.FontSpec.IsBold = true; text.FontSpec.IsItalic = true; text.Location.CoordinateFrame = CoordType.XChartFractionYScale;

Page 27: Ejemplo de Acceso a Datos Con Una Base de Access

text.IsClippedToChartRect = true; myPane.GraphObjList.Add( text ); // Fill the pane background with a gradient myPane.Fill = new Fill( Color.WhiteSmoke, Color.Lavender, 0F );

// Calculate the Axis Scale Ranges zgc.AxisChange();}

Sample Code in VB

' Call this method from the Form_Load method, passing your ZedGraphControl Public Sub CreateChart(ByVal zgc As ZedGraphControl)

Dim myPane As GraphPane = zgc.GraphPane

' Set the title and axis labels myPane.Title.Text = "Line Graph with Band Demo" myPane.XAxis.Title.Text = "Sequence" myPane.YAxis.Title.Text = "Temperature, C"

' Enter some random data values Dim y() As Double = {100, 115, 75, 22, 98, 40, 10} Dim y2() As Double = {90, 100, 95, 35, 80, 35, 35} Dim y3() As Double = {80, 110, 65, 15, 54, 67, 18} Dim x() As Double = {100, 200, 300, 400, 500, 600, 700}

' Fill the axis background with a color gradient myPane.Chart.Fill = New Fill(Color.FromArgb(255, 255, 245), Color.FromArgb(255, 255, 190), 90.0F)

' Generate a red curve with "Curve 1" in the legend Dim myCurve As LineItem = myPane.AddCurve("Curve 1", x, y, Color.Red) ' Make the symbols opaque by filling them with white myCurve.Symbol.Fill = New Fill(Color.White) ' Generate a blue curve with "Curve 2" in the legend myCurve = myPane.AddCurve("Curve 2", x, y2, Color.Blue) ' Make the symbols opaque by filling them with white myCurve.Symbol.Fill = New Fill(Color.White)

' Generate a green curve with "Curve 3" in the legend myCurve = myPane.AddCurve("Curve 3", x, y3, Color.Green) ' Make the symbols opaque by filling them with white myCurve.Symbol.Fill = New Fill(Color.White)

' Manually set the x axis range

Page 28: Ejemplo de Acceso a Datos Con Una Base de Access

myPane.XAxis.Scale.Min = 0 myPane.XAxis.Scale.Max = 800 ' Display the Y axis grid lines myPane.YAxis.MajorGrid.IsVisible = True myPane.YAxis.MinorGrid.IsVisible = True

' Draw a box item to highlight a value range Dim box As BoxObj = New BoxObj(0, 100, 1, 30, Color.Empty, Color.FromArgb(150, Color.LightGreen)) box.Fill = New Fill(Color.White, Color.FromArgb(200, Color.LightGreen), 45.0F)

' Use the BehindAxis zorder to draw the highlight beneath the grid lines box.ZOrder = ZOrder.E_BehindCurves ' Make sure that the boxObj does not extend outside the chart rect if the chart is zoomed box.IsClippedToChartRect = True ' Use a hybrid coordinate system so the X axis always covers the full x range ' from chart fraction 0.0 to 1.0 box.Location.CoordinateFrame = CoordType.XChartFractionYScale myPane.GraphObjList.Add(box)

' Add a text item to label the highlighted range Dim Text As TextObj = New TextObj("Optimal\nRange", 0.95F, 85, CoordType.AxisXYScale, AlignH.Right, AlignV.Center) Text.FontSpec.Fill.IsVisible = False Text.FontSpec.Border.IsVisible = False Text.FontSpec.IsBold = True Text.FontSpec.IsItalic = True Text.Location.CoordinateFrame = CoordType.XChartFractionYScale Text.IsClippedToChartRect = True myPane.GraphObjList.Add(Text)

' Fill the pane background with a gradient myPane.Fill = New Fill(Color.WhiteSmoke, Color.Lavender, 0.0F)

' Calculate the Axis Scale Ranges zgc.AxisChange() End Sub

Go back to Sample Graphs

Multi-Y DemoNOTE: The code on this page is for ZedGraph version 5. You can view the code for version

4.3 here.

Page 29: Ejemplo de Acceso a Datos Con Una Base de Access

Sample Code in C#

// Call this method from the Form_Load method, passing your ZedGraphControl instancepublic void CreateChart( ZedGraphControl zgc ){ // Get a reference to the GraphPane GraphPane myPane = zgc.GraphPane;

// Set the titles and axis labels myPane.Title.Text = "Demonstration of Multi Y Graph"; myPane.XAxis.Title.Text = "Time, s"; myPane.YAxis.Title.Text = "Velocity, m/s"; myPane.Y2Axis.Title.Text = "Acceleration, m/s2"; // Make up some data points based on the Sine function PointPairList vList = new PointPairList(); PointPairList aList = new PointPairList(); PointPairList dList = new PointPairList(); PointPairList eList = new PointPairList(); // Fabricate some data values for ( int i=0; i<30; i++ ) { double time = (double) i; double acceleration = 2.0; double velocity = acceleration * time;

Page 30: Ejemplo de Acceso a Datos Con Una Base de Access

double distance = acceleration * time * time / 2.0; double energy = 100.0 * velocity * velocity / 2.0; aList.Add( time, acceleration ); vList.Add( time, velocity ); eList.Add( time, energy ); dList.Add( time, distance ); } // Generate a red curve with diamond symbols, and "Velocity" in the legend LineItem myCurve = myPane.AddCurve( "Velocity", vList, Color.Red, SymbolType.Diamond ); // Fill the symbols with white myCurve.Symbol.Fill = new Fill( Color.White ); // Generate a blue curve with circle symbols, and "Acceleration" in the legend myCurve = myPane.AddCurve( "Acceleration", aList, Color.Blue, SymbolType.Circle ); // Fill the symbols with white myCurve.Symbol.Fill = new Fill( Color.White ); // Associate this curve with the Y2 axis myCurve.IsY2Axis = true; // Generate a green curve with square symbols, and "Distance" in the legend myCurve = myPane.AddCurve( "Distance", dList, Color.Green, SymbolType.Square ); // Fill the symbols with white myCurve.Symbol.Fill = new Fill( Color.White ); // Associate this curve with the second Y axis myCurve.YAxisIndex = 1; // Generate a Black curve with triangle symbols, and "Energy" in the legend myCurve = myPane.AddCurve( "Energy", eList, Color.Black, SymbolType.Triangle ); // Fill the symbols with white myCurve.Symbol.Fill = new Fill( Color.White ); // Associate this curve with the Y2 axis myCurve.IsY2Axis = true; // Associate this curve with the second Y2 axis myCurve.YAxisIndex = 1; // Show the x axis grid myPane.XAxis.MajorGrid.IsVisible = true; // Make the Y axis scale red myPane.YAxis.Scale.FontSpec.FontColor = Color.Red; myPane.YAxis.Title.FontSpec.FontColor = Color.Red;

Page 31: Ejemplo de Acceso a Datos Con Una Base de Access

// turn off the opposite tics so the Y tics don't show up on the Y2 axis myPane.YAxis.MajorTic.IsOpposite = false; myPane.YAxis.MinorTic.IsOpposite = false; // Don't display the Y zero line myPane.YAxis.MajorGrid.IsZeroLine = false; // Align the Y axis labels so they are flush to the axis myPane.YAxis.Scale.Align = AlignP.Inside; myPane.YAxis.Scale.Max = 100; // Enable the Y2 axis display myPane.Y2Axis.IsVisible = true; // Make the Y2 axis scale blue myPane.Y2Axis.Scale.FontSpec.FontColor = Color.Blue; myPane.Y2Axis.Title.FontSpec.FontColor = Color.Blue; // turn off the opposite tics so the Y2 tics don't show up on the Y axis myPane.Y2Axis.MajorTic.IsOpposite = false; myPane.Y2Axis.MinorTic.IsOpposite = false; // Display the Y2 axis grid lines myPane.Y2Axis.MajorGrid.IsVisible = true; // Align the Y2 axis labels so they are flush to the axis myPane.Y2Axis.Scale.Align = AlignP.Inside; myPane.Y2Axis.Scale.Min = 1.5; myPane.Y2Axis.Scale.Max = 3; // Create a second Y Axis, green YAxis yAxis3 = new YAxis( "Distance, m" ); myPane.YAxisList.Add( yAxis3 ); yAxis3.Scale.FontSpec.FontColor = Color.Green; yAxis3.Title.FontSpec.FontColor = Color.Green; yAxis3.Color = Color.Green; // turn off the opposite tics so the Y2 tics don't show up on the Y axis yAxis3.MajorTic.IsInside = false; yAxis3.MinorTic.IsInside = false; yAxis3.MajorTic.IsOpposite = false; yAxis3.MinorTic.IsOpposite = false; // Align the Y2 axis labels so they are flush to the axis yAxis3.Scale.Align = AlignP.Inside; Y2Axis yAxis4 = new Y2Axis( "Energy" ); yAxis4.IsVisible = true; myPane.Y2AxisList.Add( yAxis4 ); // turn off the opposite tics so the Y2 tics don't show up on the Y axis yAxis4.MajorTic.IsInside = false; yAxis4.MinorTic.IsInside = false; yAxis4.MajorTic.IsOpposite = false; yAxis4.MinorTic.IsOpposite = false; // Align the Y2 axis labels so they are flush to the axis

Page 32: Ejemplo de Acceso a Datos Con Una Base de Access

yAxis4.Scale.Align = AlignP.Inside; yAxis4.Type = AxisType.Log; yAxis4.Scale.Min = 100; // Fill the axis background with a gradient myPane.Chart.Fill = new Fill( Color.White, Color.LightGoldenrodYellow, 45.0f ); zgc.AxisChange();}

Sample Code in VB

' Call this method from the Form_Load method, passing your ZedGraphControlPrivate Sub CreateGraph(ByVal zgc as ZedGraphControl) Dim myPane As GraphPane = zgc.GraphPane

' Set the titles and axis labels myPane.Title.Text = "Demonstration of Multi Y Graph" myPane.XAxis.Title.Text = "Time, s" myPane.YAxis.Title.Text = "Velocity, m/s" myPane.Y2Axis.Title.Text = "Acceleration, m/s2" ' Make up some data points based on the Sine function Dim vList As New PointPairList() Dim aList As New PointPairList() Dim dList As New PointPairList() Dim eList As New PointPairList() ' Fabricate some data values Dim i As Integer Dim time As Double, acceleration As Double, velocity As Double Dim distance As Double, energy As Double For i = 0 To 30 time = i acceleration = 2.0 velocity = acceleration * time distance = acceleration * time * time / 2.0 energy = 100.0 * velocity * velocity / 2.0 aList.Add(time, acceleration) vList.Add(time, velocity) eList.Add(time, energy) dList.Add(time, distance) Next i ' Generate a red curve with diamond symbols, and "Velocity" in the legend Dim myCurve As LineItem = myPane.AddCurve("Velocity", vList, Color.Red, SymbolType.Diamond)

Page 33: Ejemplo de Acceso a Datos Con Una Base de Access

' Fill the symbols with white myCurve.Symbol.Fill = New Fill(Color.White) ' Generate a blue curve with circle symbols, and "Acceleration" in the legend myCurve = myPane.AddCurve("Acceleration", aList, Color.Blue, SymbolType.Circle) ' Fill the symbols with white myCurve.Symbol.Fill = New Fill(Color.White) ' Associate this curve with the Y2 axis myCurve.IsY2Axis = True ' Generate a green curve with square symbols, and "Distance" in the legend myCurve = myPane.AddCurve("Distance", dList, Color.Green, SymbolType.Square) ' Fill the symbols with white myCurve.Symbol.Fill = New Fill(Color.White) ' Associate this curve with the second Y axis myCurve.YAxisIndex = 1 ' Generate a Black curve with triangle symbols, and "Energy" in the legend myCurve = myPane.AddCurve("Energy", eList, Color.Black, SymbolType.Triangle) ' Fill the symbols with white myCurve.Symbol.Fill = New Fill(Color.White) ' Associate this curve with the Y2 axis myCurve.IsY2Axis = True ' Associate this curve with the second Y2 axis myCurve.YAxisIndex = 1 ' Show the x axis grid myPane.XAxis.MajorGrid.IsVisible = True ' Make the Y axis scale red myPane.YAxis.Scale.FontSpec.FontColor = Color.Red myPane.YAxis.Title.FontSpec.FontColor = Color.Red ' turn off the opposite tics so the Y tics don't show up on the Y2 axis myPane.YAxis.MajorTic.IsOpposite = False myPane.YAxis.MinorTic.IsOpposite = False ' Don't display the Y zero line myPane.YAxis.MajorGrid.IsZeroLine = False ' Align the Y axis labels so they are flush to the axis myPane.YAxis.Scale.Align = AlignP.Inside myPane.YAxis.Scale.Max = 100 ' Enable the Y2 axis display myPane.Y2Axis.IsVisible = True ' Make the Y2 axis scale blue

Page 34: Ejemplo de Acceso a Datos Con Una Base de Access

myPane.Y2Axis.Scale.FontSpec.FontColor = Color.Blue myPane.Y2Axis.Title.FontSpec.FontColor = Color.Blue ' turn off the opposite tics so the Y2 tics don't show up on the Y axis myPane.Y2Axis.MajorTic.IsOpposite = False myPane.Y2Axis.MinorTic.IsOpposite = False ' Display the Y2 axis grid lines myPane.Y2Axis.MajorGrid.IsVisible = True ' Align the Y2 axis labels so they are flush to the axis myPane.Y2Axis.Scale.Align = AlignP.Inside myPane.Y2Axis.Scale.Min = 1.5 myPane.Y2Axis.Scale.Max = 3 ' Create a second Y Axis, green Dim yAxis3 As New YAxis("Distance, m") myPane.YAxisList.Add(yAxis3) yAxis3.Scale.FontSpec.FontColor = Color.Green yAxis3.Title.FontSpec.FontColor = Color.Green yAxis3.Color = Color.Green ' turn off the opposite tics so the Y2 tics don't show up on the Y axis yAxis3.MajorTic.IsInside = False yAxis3.MinorTic.IsInside = False yAxis3.MajorTic.IsOpposite = False yAxis3.MinorTic.IsOpposite = False ' Align the Y2 axis labels so they are flush to the axis yAxis3.Scale.Align = AlignP.Inside Dim yAxis4 As New Y2Axis("Energy") yAxis4.IsVisible = True myPane.Y2AxisList.Add(yAxis4) ' turn off the opposite tics so the Y2 tics don't show up on the Y axis yAxis4.MajorTic.IsInside = False yAxis4.MinorTic.IsInside = False yAxis4.MajorTic.IsOpposite = False yAxis4.MinorTic.IsOpposite = False ' Align the Y2 axis labels so they are flush to the axis yAxis4.Scale.Align = AlignP.Inside yAxis4.Type = AxisType.Log yAxis4.Scale.Min = 100 ' Fill the axis background with a gradient myPane.Chart.Fill = New Fill(Color.White, Color.LightGoldenrodYellow, 45.0F) zgc.AxisChange()

End Sub

Page 35: Ejemplo de Acceso a Datos Con Una Base de Access

Point Label Demo

// Call this method from the Form_Load method, passing your ZedGraphControlpublic void CreateChart( ZedGraphControl zgc ){ GraphPane myPane = zgc.GraphPane; // Set the titles and axis labels myPane.Title.Text = "Demo of Labeled Points"; myPane.XAxis.Title.Text = "Time, Seconds"; myPane.YAxis.Title.Text = "Pressure, Psia"; // Build a PointPairList with points based on Sine wave PointPairList list = new PointPairList(); const int count = 15; for ( int i = 0; i < count; i++ ) { double x = i + 1; double y = 21.1 * ( 1.0 + Math.Sin( (double)i * 0.15 ) ); list.Add( x, y ); } // Hide the legend myPane.Legend.IsVisible = false; // Add a curve

Page 36: Ejemplo de Acceso a Datos Con Una Base de Access

LineItem curve = myPane.AddCurve( "label", list, Color.Red, SymbolType.Circle ); curve.Line.Width = 2.0F; curve.Line.IsAntiAlias = true; curve.Symbol.Fill = new Fill( Color.White ); curve.Symbol.Size = 7; // Fill the axis background with a gradient myPane.Chart.Fill = new Fill( Color.White, Color.FromArgb( 255, Color.ForestGreen ), 45.0F ); // Offset Y space between point and label // NOTE: This offset is in Y scale units, so it depends on your actual data const double offset = 1.0; // Loop to add text labels to the points for ( int i = 0; i < count; i++ ) { // Get the pointpair PointPair pt = curve.Points[i]; // Create a text label from the Y data value TextObj text = new TextObj( pt.Y.ToString( "f2" ), pt.X, pt.Y + offset, CoordType.AxisXYScale, AlignH.Left, AlignV.Center ); text.ZOrder = ZOrder.A_InFront; // Hide the border and the fill text.FontSpec.Border.IsVisible = false; text.FontSpec.Fill.IsVisible = false; //text.FontSpec.Fill = new Fill( Color.FromArgb( 100, Color.White ) ); // Rotate the text to 90 degrees text.FontSpec.Angle = 90; myPane.GraphObjList.Add( text ); } // Leave some extra space on top for the labels to fit within the chart rect myPane.YAxis.Scale.MaxGrace = 0.2; // Calculate the Axis Scale Ranges zgc.AxisChange();}

Scatter Plot Demo

Page 37: Ejemplo de Acceso a Datos Con Una Base de Access

C# Sample Code

// Call this method from the Form_Load method, passing your ZedGraphControlpublic void CreateChart( ZedGraphControl zgc ){ GraphPane myPane = zgc.GraphPane;

// Set the titles myPane.Title.Text = "Scatter Plot Demo"; myPane.XAxis.Title.Text = "Pressure, Atm"; myPane.YAxis.Title.Text = "Flow Rate, cc/hr";

// Get a random number generator Random rand = new Random();

// Populate a PointPairList with a log-based function and some random variability PointPairList list = new PointPairList(); for ( int i = 0; i < 200; i++ ) { double x = rand.NextDouble() * 20.0 + 1; double y = Math.Log( 10.0 * ( x - 1.0 ) + 1.0 ) * ( rand.NextDouble() * 0.2 + 0.9 ); list.Add( x, y ); }

// Add the curve

Page 38: Ejemplo de Acceso a Datos Con Una Base de Access

LineItem myCurve = myPane.AddCurve( "Performance", list, Color.Black, SymbolType.Diamond ); // Don't display the line (This makes a scatter plot) myCurve.Line.IsVisible = false; // Hide the symbol outline myCurve.Symbol.Border.IsVisible = false; // Fill the symbol interior with color myCurve.Symbol.Fill = new Fill( Color.Firebrick );

// Fill the background of the chart rect and pane myPane.Chart.Fill = new Fill( Color.White, Color.LightGoldenrodYellow, 45.0f ); myPane.Fill = new Fill( Color.White, Color.SlateGray, 45.0f );

zgc.AxisChange();}

VB Sample Code

'Call this method from the Form_Load method, passing your ZedGraphControl Public Sub CreateChart(ByRef zgc As ZedGraphControl)

Dim myPane As GraphPane = zgc.GraphPane

'Set the titles myPane.Title.Text = "Scatter Plot Demo" myPane.XAxis.Title.Text = "Pressure, Atm" myPane.YAxis.Title.Text = "Flow Rate, cc/hr"

'Get a random number generator Dim rand As Random = New Random()

'Populate a PointPairList with a log-based function and some random variability Dim List As PointPairList = New PointPairList() Dim i As Integer Dim x, y As Double For i = 0 To 199 x = rand.NextDouble() * 20.0 + 1 y = Math.Log(10.0 * (x - 1.0) + 1.0) * (rand.NextDouble() * 0.2 + 0.9) List.Add(x, y) Next i

'Add the curve Dim myCurve As LineItem

Page 39: Ejemplo de Acceso a Datos Con Una Base de Access

myCurve = myPane.AddCurve("Performance", List, Color.Black, SymbolType.Diamond) 'Don't display the line (This makes a scatter plot) myCurve.Line.IsVisible = False 'Hide the symbol outline myCurve.Symbol.Border.IsVisible = False 'Fill the symbol interior with color myCurve.Symbol.Fill = New Fill(Color.Firebrick)

'Fill the background of the chart rect and pane myPane.Chart.Fill = New Fill(Color.White, Color.LightGoldenrodYellow, 45.0F) myPane.Fill = New Fill(Color.White, Color.SlateGray, 45.0F)

zgc.AxisChange()

End Sub

Scatter: Dispersión.

Dual-Y DemoNOTE: The code on this page is for ZedGraph version 5. You can view the code for version

4 here.

Page 40: Ejemplo de Acceso a Datos Con Una Base de Access

// Call this method from the Form_Load method, passing your ZedGraphControlpublic void CreateChart( ZedGraphControl zgc ){ GraphPane myPane = zgc.GraphPane;

// Set the titles and axis labels myPane.Title.Text = "Demonstration of Dual Y Graph"; myPane.XAxis.Title.Text = "Time, Days"; myPane.YAxis.Title.Text = "Parameter A"; myPane.Y2Axis.Title.Text = "Parameter B"; // Make up some data points based on the Sine function PointPairList list = new PointPairList(); PointPairList list2 = new PointPairList(); for ( int i=0; i<36; i++ ) { double x = (double) i * 5.0; double y = Math.Sin( (double) i * Math.PI / 15.0 ) * 16.0; double y2 = y * 13.5; list.Add( x, y ); list2.Add( x, y2 ); } // Generate a red curve with diamond symbols, and "Alpha" in the legend LineItem myCurve = myPane.AddCurve( "Alpha", list, Color.Red, SymbolType.Diamond ); // Fill the symbols with white myCurve.Symbol.Fill = new Fill( Color.White ); // Generate a blue curve with circle symbols, and "Beta" in the legend myCurve = myPane.AddCurve( "Beta", list2, Color.Blue, SymbolType.Circle ); // Fill the symbols with white myCurve.Symbol.Fill = new Fill( Color.White ); // Associate this curve with the Y2 axis myCurve.IsY2Axis = true; // Show the x axis grid myPane.XAxis.MajorGrid.IsVisible = true; // Make the Y axis scale red myPane.YAxis.Scale.FontSpec.FontColor = Color.Red; myPane.YAxis.Title.FontSpec.FontColor = Color.Red; // turn off the opposite tics so the Y tics don't show up on the Y2 axis myPane.YAxis.MajorTic.IsOpposite = false; myPane.YAxis.MinorTic.IsOpposite = false; // Don't display the Y zero line

Page 41: Ejemplo de Acceso a Datos Con Una Base de Access

myPane.YAxis.MajorGrid.IsZeroLine = false; // Align the Y axis labels so they are flush to the axis myPane.YAxis.Scale.Align = AlignP.Inside; // Manually set the axis range myPane.YAxis.Scale.Min = -30; myPane.YAxis.Scale.Max = 30; // Enable the Y2 axis display myPane.Y2Axis.IsVisible = true; // Make the Y2 axis scale blue myPane.Y2Axis.Scale.FontSpec.FontColor = Color.Blue; myPane.Y2Axis.Title.FontSpec.FontColor = Color.Blue; // turn off the opposite tics so the Y2 tics don't show up on the Y axis myPane.Y2Axis.MajorTic.IsOpposite = false; myPane.Y2Axis.MinorTic.IsOpposite = false; // Display the Y2 axis grid lines myPane.Y2Axis.MajorGrid.IsVisible = true; // Align the Y2 axis labels so they are flush to the axis myPane.Y2Axis.Scale.Align = AlignP.Inside; // Fill the axis background with a gradient myPane.Chart.Fill = new Fill( Color.White, Color.LightGray, 45.0f ); // Calculate the Axis Scale Ranges zgc.AxisChange();}

Filled Curve DemoNOTE: The code on this page is for ZedGraph version 5. You can view the code for version

4 here.

Page 42: Ejemplo de Acceso a Datos Con Una Base de Access

// Call this method from the Form_Load method, passing your ZedGraphControlpublic void CreateChart( ZedGraphControl zgc ){ GraphPane myPane = zgc.GraphPane;

// Set the titles and axis labels myPane.Title.Text = "My Test Date Graph"; myPane.XAxis.Title.Text = "Date"; myPane.YAxis.Title.Text = "My Y Axis"; // Make up some data points from the Sine function PointPairList list = new PointPairList(); PointPairList list2 = new PointPairList(); for ( int i=0; i<36; i++ ) { double x = new XDate( 1995, i+1, 1 ); double y = Math.Sin( (double) i * Math.PI / 15.0 ); double y2 = 2 * y; list.Add( x, y ); list2.Add( x, y2 ); } // Generate a blue curve with circle symbols, and "My Curve 2" in the legend

Page 43: Ejemplo de Acceso a Datos Con Una Base de Access

LineItem myCurve2 = myPane.AddCurve( "My Curve 2", list, Color.Blue, SymbolType.Circle ); // Fill the area under the curve with a white-red gradient at 45 degrees myCurve2.Line.Fill = new Fill( Color.White, Color.Red, 45F ); // Make the symbols opaque by filling them with white myCurve2.Symbol.Fill = new Fill( Color.White ); // Generate a red curve with diamond symbols, and "My Curve" in the legend LineItem myCurve = myPane.AddCurve( "My Curve", list2, Color.MediumVioletRed, SymbolType.Diamond ); // Fill the area under the curve with a white-green gradient myCurve.Line.Fill = new Fill( Color.White, Color.Green ); // Make the symbols opaque by filling them with white myCurve.Symbol.Fill = new Fill( Color.White ); // Set the XAxis to date type myPane.XAxis.Type = AxisType.Date; // Fill the axis background with a color gradient myPane.Chart.Fill = new Fill( Color.White, Color.LightGoldenrodYellow, 45F ); // Calculate the Axis Scale Ranges zgc.AxisChange();}

Gradient-By-Value DemoNOTE: The code on this page is for ZedGraph version 5. You can view the code for version

4 here.

Page 44: Ejemplo de Acceso a Datos Con Una Base de Access

C# Sample Code

// Call this method from the Form_Load method, passing your ZedGraphControlpublic void CreateChart( ZedGraphControl zgc ){ GraphPane myPane = zgc.GraphPane;

// Set the title and axis labels myPane.Title.Text = "PVT Properties"; myPane.XAxis.Title.Text = "Pressure (atm)"; myPane.YAxis.Title.Text = "Temperature (C)"; // Enter some calculated data constants PointPairList list1 = new PointPairList(); list1.Add( 13.03, 59.26, 31.67 ); list1.Add( 18.73, 75.62, 23.34 ); list1.Add( 16.94, 11.09, 21.04 ); list1.Add( 11.66, 29.68, 32.19 ); list1.Add( 12.94, 27.73, 28.94 ); list1.Add( 18.04, 54.71, 22.76 ); list1.Add( 17.36, 66.92, 24.51 ); list1.Add( 13.19, 27.65, 28.39 ); list1.Add( 12.79, 41.93, 30.6 ); list1.Add( 19.66, 52.21, 20.79 ); list1.Add( 17.17, 41.82, 22.98 );

Page 45: Ejemplo de Acceso a Datos Con Una Base de Access

list1.Add( 12.57, 25.59, 29.53 ); list1.Add( 18.74, 45.86, 21.36 ); list1.Add( 12.66, 8.73, 27.71 ); list1.Add( 13.29, 26.49, 28.07 ); list1.Add( 12.47, 22.58, 29.48 ); list1.Add( 14.76, 38.87, 26.36 ); list1.Add( 22.54, 75.93, 19.5 ); list1.Add( 14.38, 72.0, 29.88 ); list1.Add( 12.01, 12.95, 29.58 ); list1.Add( 14.96, 8.99, 23.6 ); list1.Add( 17.58, 88.99, 25.76 ); list1.Add( 15.4, 34.66, 24.97 ); list1.Add( 15.39, 19.74, 23.79 ); list1.Add( 19.88, 43.63, 20.03 ); list1.Add( 12.42, 26.17, 29.93 ); list1.Add( 12.91, 21.17, 28.37 ); list1.Add( 16.48, 62.67, 25.47 ); list1.Add( 12.05, 21.33, 30.36 ); list1.Add( 17.4, 95.91, 26.52 ); list1.Add( 17.92, 63.01, 23.51 ); list1.Add( 15.74, 21.08, 23.4 ); list1.Add( 14.57, 20.99, 25.21 ); list1.Add( 16.08, 30.12, 23.58 ); list1.Add( 17.44, 31.23, 21.9 ); list1.Add( 15.79, 44.7, 25.19 ); list1.Add( 13.67, 42.4, 28.74 ); list1.Add( 15.98, 55.96, 25.74 ); list1.Add( 15.41, 33.06, 24.83 ); list1.Add( 14.37, 41.31, 27.28 ); list1.Add( 13.99, 59.27, 29.58 ); list1.Add( 11.43, 47.13, 34.65 ); list1.Add( 15.21, 46.2, 26.21 ); list1.Add( 20.08, 59.66, 20.82 ); list1.Add( 16.45, 42.42, 24 ); list1.Add( 11.76, 6.28, 29.51 ); list1.Add( 18.66, 62.34, 22.56 ); list1.Add( 14.91, 32.14, 25.58 ); list1.Add( 14.2, 50.85, 28.43 ); list1.Add( 14.99, 46.38, 26.6 ); list1.Add( 23.55, 80.77, 18.93 ); list1.Add( 13.4, 21.14, 27.34 ); list1.Add( 15.39, 33.16, 24.88 ); list1.Add( 20.4, 38.22, 19.21 ); list1.Add( 13.63, 58.78, 30.28 ); list1.Add( 13.23, 70.03, 32.2 ); list1.Add( 15.25, 39.34, 25.62 ); list1.Add( 14.92, 13.68, 24.04 ); list1.Add( 23.81, 85.41, 18.93 ); list1.Add( 18.5, 28.86, 20.48 ); list1.Add( 14.11, 98.51, 32.72 ); list1.Add( 17.22, 94.7, 26.68 );

Page 46: Ejemplo de Acceso a Datos Con Una Base de Access

list1.Add( 22.94, 87.21, 19.74 ); list1.Add( 12.38, 72.77, 34.61 ); list1.Add( 13.26, 71.69, 32.26 ); list1.Add( 15.07, 5.37, 23.11 ); list1.Add( 16.2, 70.1, 26.45 ); list1.Add( 12.81, 16.61, 28.14 ); list1.Add( 11.63, 10.06, 30.23 ); list1.Add( 13.84, 85.76, 32.23 ); list1.Add( 14.8, 6.93, 23.67 ); list1.Add( 13.6, 26.68, 27.5 ); list1.Add( 13.65, 63.22, 30.64 ); list1.Add( 24.85, 97.2, 18.77 ); list1.Add( 13.8, 44.99, 28.71 ); list1.Add( 20.02, 96.99, 23.19 ); list1.Add( 16.91, 50.47, 23.94 ); list1.Add( 11.94, 32.23, 31.72 ); list1.Add( 19.97, 77.09, 22 ); list1.Add( 14.21, 98.48, 32.49 ); list1.Add( 17.66, 38.76, 22.15 ); list1.Add( 17.23, 42.5, 22.96 ); list1.Add( 14.43, 8.97, 24.43 ); list1.Add( 14.94, 60.76, 27.87 ); // Generate a red curve with diamond symbols, and "Gas Data" in the legend LineItem myCurve = myPane.AddCurve( "Gas Data", list1, Color.Red, SymbolType.Diamond ); myCurve.Symbol.Size = 12; // Set up a red-blue color gradient to be used for the fill myCurve.Symbol.Fill = new Fill( Color.Red, Color.Blue ); // Turn off the symbol borders myCurve.Symbol.Border.IsVisible = false; // Instruct ZedGraph to fill the symbols by selecting a color out of the // red-blue gradient based on the Z value. A value of 19 or less will be red, // a value of 34 or more will be blue, and values in between will be a // linearly apportioned color between red and blue. myCurve.Symbol.Fill.Type = FillType.GradientByZ; myCurve.Symbol.Fill.RangeMin = 19; myCurve.Symbol.Fill.RangeMax = 34; // Turn off the line, so the curve will by symbols only myCurve.Line.IsVisible = false; // Display a text item with "MW = 34" on the graph TextObj text = new TextObj( "MW = 34", 12.9F, 110, CoordType.AxisXYScale ); text.FontSpec.FontColor = Color.Blue; text.FontSpec.Border.IsVisible = false; text.FontSpec.Fill.IsVisible = false;

Page 47: Ejemplo de Acceso a Datos Con Una Base de Access

text.FontSpec.Size = 14; myPane.GraphObjList.Add( text ); // Display a text item with "MW = 19" on the graph text = new TextObj( "MW = 19", 25, 110, CoordType.AxisXYScale ); text.FontSpec.FontColor = Color.Red; text.FontSpec.Border.IsVisible = false; text.FontSpec.Fill.IsVisible = false; text.FontSpec.Size = 14; myPane.GraphObjList.Add( text ); // Show the X and Y grids myPane.XAxis.MajorGrid.IsVisible = true; myPane.YAxis.MajorGrid.IsVisible = true; // Set the x and y scale and title font sizes to 14 myPane.XAxis.Scale.FontSpec.Size = 14; myPane.XAxis.Title.FontSpec.Size = 14; myPane.YAxis.Scale.FontSpec.Size = 14; myPane.YAxis.Title.FontSpec.Size = 14; // Set the GraphPane title font size to 16 myPane.Title.FontSpec.Size = 16; // Turn off the legend myPane.Legend.IsVisible = false; // Fill the axis background with a color gradient myPane.Chart.Fill = new Fill( Color.White, Color.FromArgb( 255, 255, 166), 90F ); // Calculate the Axis Scale Ranges zgc.AxisChange();}

VB Sample Code

' Call this method from the Form_Load method, passing your ZedGraphControlPrivate Sub CreateGraph(ByVal zgc as ZedGraphControl) Dim myPane As GraphPane = zgc.GraphPane

' Set the title and axis labels myPane.Title.Text = "PVT Properties" myPane.XAxis.Title.Text = "Pressure (atm)" myPane.YAxis.Title.Text = "Temperature (C)"

' Enter some calculated data constants Dim list1 As New PointPairList()

list1.Add( 13.03, 59.26, 31.67 )

Page 48: Ejemplo de Acceso a Datos Con Una Base de Access

list1.Add( 18.73, 75.62, 23.34 ) list1.Add( 16.94, 11.09, 21.04 ) list1.Add( 11.66, 29.68, 32.19 ) list1.Add( 12.94, 27.73, 28.94 ) list1.Add( 18.04, 54.71, 22.76 ) list1.Add( 17.36, 66.92, 24.51 ) list1.Add( 13.19, 27.65, 28.39 ) list1.Add( 12.79, 41.93, 30.6 ) list1.Add( 19.66, 52.21, 20.79 ) list1.Add( 17.17, 41.82, 22.98 ) list1.Add( 12.57, 25.59, 29.53 ) list1.Add( 18.74, 45.86, 21.36 ) list1.Add( 12.66, 8.73, 27.71 ) list1.Add( 13.29, 26.49, 28.07 ) list1.Add( 12.47, 22.58, 29.48 ) list1.Add( 14.76, 38.87, 26.36 ) list1.Add( 22.54, 75.93, 19.5 ) list1.Add( 14.38, 72.0, 29.88 ) list1.Add( 12.01, 12.95, 29.58 ) list1.Add( 14.96, 8.99, 23.6 ) list1.Add( 17.58, 88.99, 25.76 ) list1.Add( 15.4, 34.66, 24.97 ) list1.Add( 15.39, 19.74, 23.79 ) list1.Add( 19.88, 43.63, 20.03 ) list1.Add( 12.42, 26.17, 29.93 ) list1.Add( 12.91, 21.17, 28.37 ) list1.Add( 16.48, 62.67, 25.47 ) list1.Add( 12.05, 21.33, 30.36 ) list1.Add( 17.4, 95.91, 26.52 ) list1.Add( 17.92, 63.01, 23.51 ) list1.Add( 15.74, 21.08, 23.4 ) list1.Add( 14.57, 20.99, 25.21 ) list1.Add( 16.08, 30.12, 23.58 ) list1.Add( 17.44, 31.23, 21.9 ) list1.Add( 15.79, 44.7, 25.19 ) list1.Add( 13.67, 42.4, 28.74 ) list1.Add( 15.98, 55.96, 25.74 ) list1.Add( 15.41, 33.06, 24.83 ) list1.Add( 14.37, 41.31, 27.28 ) list1.Add( 13.99, 59.27, 29.58 ) list1.Add( 11.43, 47.13, 34.65 ) list1.Add( 15.21, 46.2, 26.21 ) list1.Add( 20.08, 59.66, 20.82 ) list1.Add( 16.45, 42.42, 24 ) list1.Add( 11.76, 6.28, 29.51 ) list1.Add( 18.66, 62.34, 22.56 ) list1.Add( 14.91, 32.14, 25.58 ) list1.Add( 14.2, 50.85, 28.43 ) list1.Add( 14.99, 46.38, 26.6 ) list1.Add( 23.55, 80.77, 18.93 ) list1.Add( 13.4, 21.14, 27.34 )

Page 49: Ejemplo de Acceso a Datos Con Una Base de Access

list1.Add( 15.39, 33.16, 24.88 ) list1.Add( 20.4, 38.22, 19.21 ) list1.Add( 13.63, 58.78, 30.28 ) list1.Add( 13.23, 70.03, 32.2 ) list1.Add( 15.25, 39.34, 25.62 ) list1.Add( 14.92, 13.68, 24.04 ) list1.Add( 23.81, 85.41, 18.93 ) list1.Add( 18.5, 28.86, 20.48 ) list1.Add( 14.11, 98.51, 32.72 ) list1.Add( 17.22, 94.7, 26.68 ) list1.Add( 22.94, 87.21, 19.74 ) list1.Add( 12.38, 72.77, 34.61 ) list1.Add( 13.26, 71.69, 32.26 ) list1.Add( 15.07, 5.37, 23.11 ) list1.Add( 16.2, 70.1, 26.45 ) list1.Add( 12.81, 16.61, 28.14 ) list1.Add( 11.63, 10.06, 30.23 ) list1.Add( 13.84, 85.76, 32.23 ) list1.Add( 14.8, 6.93, 23.67 ) list1.Add( 13.6, 26.68, 27.5 ) list1.Add( 13.65, 63.22, 30.64 ) list1.Add( 24.85, 97.2, 18.77 ) list1.Add( 13.8, 44.99, 28.71 ) list1.Add( 20.02, 96.99, 23.19 ) list1.Add( 16.91, 50.47, 23.94 ) list1.Add( 11.94, 32.23, 31.72 ) list1.Add( 19.97, 77.09, 22 ) list1.Add( 14.21, 98.48, 32.49 ) list1.Add( 17.66, 38.76, 22.15 ) list1.Add( 17.23, 42.5, 22.96 ) list1.Add( 14.43, 8.97, 24.43 ) list1.Add( 14.94, 60.76, 27.87 )

' Generate a red curve with diamond symbols, and "Gas Data" in the legend Dim myCurve As LineItem = myPane.AddCurve("Gas Data", list1, Color.Red, _ SymbolType.Diamond) myCurve.Symbol.Size = 12 ' Set up a red-blue color gradient to be used for the fill myCurve.Symbol.Fill = New Fill(Color.Red, Color.Blue) ' Turn off the symbol borders myCurve.Symbol.Border.IsVisible = False ' Instruct ZedGraph to fill the symbols by selecting a color out of the ' red-blue gradient based on the Z value. A value of 19 or less will be red, ' a value of 34 or more will be blue, and values in between will be a ' linearly apportioned color between red and blue. myCurve.Symbol.Fill.Type = FillType.GradientByZ

Page 50: Ejemplo de Acceso a Datos Con Una Base de Access

myCurve.Symbol.Fill.RangeMin = 19 myCurve.Symbol.Fill.RangeMax = 34 ' Turn off the line, so the curve will by symbols only myCurve.Line.IsVisible = False

' Display a text item with "MW = 34" on the graph Dim text As New TextObj("MW = 34", 12.9F, 110, CoordType.AxisXYScale) text.FontSpec.FontColor = Color.Blue text.FontSpec.Border.IsVisible = False text.FontSpec.Fill.IsVisible = False text.FontSpec.Size = 14 myPane.GraphObjList.Add(text)

' Display a text item with "MW = 19" on the graph text = New TextObj("MW = 19", 25, 110, CoordType.AxisXYScale) text.FontSpec.FontColor = Color.Red text.FontSpec.Border.IsVisible = False text.FontSpec.Fill.IsVisible = False text.FontSpec.Size = 14 myPane.GraphObjList.Add(text)

' Show the X and Y grids myPane.XAxis.MajorGrid.IsVisible = True myPane.YAxis.MajorGrid.IsVisible = True

' Set the x and y scale and title font sizes to 14 myPane.XAxis.Scale.FontSpec.Size = 14 myPane.XAxis.Title.FontSpec.Size = 14 myPane.YAxis.Scale.FontSpec.Size = 14 myPane.YAxis.Title.FontSpec.Size = 14 ' Set the GraphPane title font size to 16 myPane.Title.FontSpec.Size = 16 ' Turn off the legend myPane.Legend.IsVisible = False

' Fill the axis background with a color gradient myPane.Chart.Fill = New Fill(Color.White, Color.FromArgb(255, 255, 166), 90.0F)

' Calculate the Axis Scale Ranges zgc.AxisChange()End Sub

Go back to Sample Graphs

Line Stack Demo

Page 51: Ejemplo de Acceso a Datos Con Una Base de Access

NOTE: The code on this page is for ZedGraph version 5. You can view the code for version

4 here.

// Call this method from the Form_Load method, passing your ZedGraphControlpublic void CreateChart( ZedGraphControl zgc ){ GraphPane myPane = zgc.GraphPane;

// Set the title and axis labels myPane.Title.Text = "Wacky Widget Company\nProduction Report"; myPane.XAxis.Title.Text = "Time, Days\n(Since Plant Construction Startup)"; myPane.YAxis.Title.Text = "Widget Production\n(units/hour)"; // enter some arbitrary data points double[] x = { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 }; double[] y = { 20, 10, 50, 25, 35, 75, 90, 40, 33, 50 }; // Add a green curve LineItem curve; curve = myPane.AddCurve( "Larry", x, y, Color.Green, SymbolType.Circle ); curve.Line.Width = 1.5F; // Make the curve smooth with cardinal splines curve.Line.IsSmooth = true; curve.Line.SmoothTension = 0.6F;

Page 52: Ejemplo de Acceso a Datos Con Una Base de Access

// Fill the symbols with white to make them opaque curve.Symbol.Fill = new Fill( Color.White ); curve.Symbol.Size = 10; // Add a second curve double[] y3 = { 5.2, 49.0, 33.8, 88.57, 99.9, 36.8, 22.1, 34.3, 10.4, 17.5 }; curve = myPane.AddCurve( "Moe", x, y3, Color.FromArgb( 200, 55, 135), SymbolType.Triangle ); curve.Line.Width = 1.5F; // Fill the symbols with white to make them opaque curve.Symbol.Fill = new Fill( Color.White ); // Fill the area between the curves with color curve.Line.Fill = new Fill( Color.White, Color.FromArgb( 160, 230, 145, 205), 90F ); curve.Symbol.Size = 10; // Fill the pane background with a color gradient myPane.Fill = new Fill( Color.WhiteSmoke, Color.Lavender, 0F ); // Fill the axis background with a color gradient myPane.Chart.Fill = new Fill( Color.FromArgb( 255, 255, 245), Color.FromArgb( 255, 255, 190), 90F ); // Show the x and y axis gridlines myPane.XAxis.MajorGrid.IsVisible = true; myPane.YAxis.MajorGrid.IsVisible = true; // Use the stacked curve type so the curve values sum up // this also causes only the area between the curves to be filled, rather than // the area between each curve and the x axis myPane.LineType = LineType.Stack; // Calculate the Axis Scale Ranges zgc.AxisChange();}

Go back to Sample Graphs

Smooth Chart DemoNOTE: The code on this page is for ZedGraph version 5. You can view the code for version

4 here.

Page 53: Ejemplo de Acceso a Datos Con Una Base de Access

// Call this method from the Form_Load method, passing your ZedGraphControlpublic void CreateChart( ZedGraphControl zgc ){ GraphPane myPane = zgc.GraphPane;

// set the title and axis labels myPane.Title.Text = "Smooth Line Demo"; myPane.XAxis.Title.Text = "Value"; myPane.YAxis.Title.Text = "Time"; // Enter some arbitrary data double[] x = { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 }; double[] y = { 20, 10, 50, 25, 35, 75, 90, 40, 33, 50 }; // Add a smoothed curve LineItem curve = myPane.AddCurve( "Smooth (Tension=0.5)", x, y, Color.Red, SymbolType.Diamond ); curve.Symbol.Fill = new Fill( Color.White ); curve.Symbol.Size = 5; // activate the cardinal spline smoothing curve.Line.IsSmooth = true; curve.Line.SmoothTension = 0.5F; // Add a forward step type curve curve = myPane.AddCurve( "Forward Step", x, y, Color.Green, SymbolType.Circle );

Page 54: Ejemplo de Acceso a Datos Con Una Base de Access

curve.Symbol.Fill = new Fill( Color.White ); curve.Symbol.Size = 5; curve.Line.StepType = StepType.ForwardStep; // add a rearward step type curve curve = myPane.AddCurve( "Rearward Step", x, y, Color.Gold, SymbolType.Square ); curve.Symbol.Fill = new Fill( Color.White ); curve.Symbol.Size = 5; curve.Line.StepType = StepType.RearwardStep; // add a regular non-step, non-smooth curve curve = myPane.AddCurve( "Non-Step", x, y, Color.Blue, SymbolType.Triangle ); curve.Symbol.Fill = new Fill( Color.White ); curve.Symbol.Size = 5; // Fill the axis background with a color gradient myPane.Chart.Fill = new Fill( Color.White, Color.LightGray, 45.0F ); // Calculate the Axis Scale Ranges zgc.AxisChange();}

Go back to Sample Graphs

SampleMultiPointList DemoNOTE: The code on this page is for ZedGraph version 5. You can view the code for version

4 here.

Page 55: Ejemplo de Acceso a Datos Con Una Base de Access

// Call this method from the Form_Load method, passing your ZedGraphControlpublic void CreateChart( ZedGraphControl zgc ){ GraphPane myPane = zgc.GraphPane;

// Set the titles and axis labels myPane.Title.Text = "SampleMultiPointList (IPointList) Demo"; myPane.XAxis.Title.Text = "Time, seconds"; myPane.YAxis.Title.Text = "Distance (m), or Velocity (m/s)"; // Create a new SampleMultiPointList (see SampleMultiPointList.cs for details) SampleMultiPointList myList = new SampleMultiPointList(); // For the first list, specify that the Y data to be plotted will be the distance myList.YData = PerfDataType.Distance; // note how it does not matter that we created the second list before actually // adding the data -- this is because the cloned list shares data with the // original SampleMultiPointList myList2 = new SampleMultiPointList( myList ); // For the second list, specify that the Y data to be plotted will be the velocity myList2.YData = PerfDataType.Velocity;

Page 56: Ejemplo de Acceso a Datos Con Una Base de Access

// Populate the dataset using some calculated values for ( int i=0; i<20; i++ ) { double time = (double) i; double acceleration = 1.0; double velocity = acceleration * time; double distance = acceleration * time * time / 2.0; PerformanceData perfData = new PerformanceData( time, distance, velocity, acceleration ); myList.Add( perfData ); } // Add two curves to the graph myPane.AddCurve( "Distance", myList, Color.Blue ); myPane.AddCurve( "Velocity", myList2, Color.Red ); // Fill the axis background with a color gradient myPane.Chart.Fill = new Fill( Color.White, Color.LightGoldenrodYellow, 45.0F ); zgc.AxisChange();}

Go back to Sample Graphs

La página : Zed Graph control

 

En este link se encuentran los ejemplos : Code Examples . Si desde el internet explorer no te permite seleccionar el código fuente para copiarlo y hacer las pruebas , abrir la página pero en otro navegador , como el Mozilla Firefox por ejemplo

Nota. al añadir la referencia de la dll , si no aparece el control en la lista de controles, hacer clic derecho en el cuadro de herramientas en la ficha general

 

Page 57: Ejemplo de Acceso a Datos Con Una Base de Access

después seleccionar: Elegir elementos, y desde la solapa "componentes de .Net Framework " incluir la dll

Nota importante: Para usar la dll desde .NET 2.0, usar la versión 5.0. Para el FrameWork 1.1, la versión 4.5

JUN13

2009

ZedGraph C# Graph Data Export to CSV Using a Custom Context MenuTagged Under : tutorials, Visual C#, Visual StudioPosted in Visual C#, tutorials by rajeev

In continuation of my earlier post on ZedGraph example which plots a sinosoidal graph, I have extended it further to:Add a new custom menu item in context menu(which appears on right click on the graph)

Export Graph plot data to CSV (coma separated values) file. Which can be opened by spreadsheets such as Microsoft Excel and Open Office calc.

Page 58: Ejemplo de Acceso a Datos Con Una Base de Access

For the custom context menu, the code has been derived from ZedGraph Wikipage. The following is the code of the Windows Form which has the ZedGraph control.view plain copy to clipboard print ?

1. using System;  2. using System.Collections.Generic;  3. using System.ComponentModel;  4. using System.Data;  5. using System.Drawing;  6. using System.Text;  7. using System.Windows.Forms;  8. using ZedGraph;  9. using System.IO;  10.   11. namespace ZedGraphTest  12. {  13. public partial class Form1 : Form  14. {  15. private PointPairList m_pointPairList;  16. //CSV Writer  17. private StreamWriter m_CSVWriter;  18.   19. public Form1()  20. {  21. InitializeComponent();  22. CreateGraph();  23. SetSize();  24.   25. //csv  26. zedGraphControl.ContextMenuBuilder +=  27. new ZedGraphControl.ContextMenuBuilderEventHandler(MyContextMenuBuilder);  28. }  29.   30. private void CreateGraph()  31. {  32. GraphPane myPane = zedGraphControl.GraphPane;  33.   34. // Set the titles and axis labels  35. myPane.Title.Text = "ZedGraph Test";  36. myPane.XAxis.Title.Text = "theta (angle)";  37. myPane.YAxis.Title.Text = "Sin (theta)";  38.   39. // Make up some data points from the Sine function  40. m_pointPairList = new PointPairList();  41. for (double x = 0; x <= 360; x += 10)  42. {  43. double y = Math.Sin(x * Math.PI / 180.0);  44.   45. m_pointPairList.Add(x, y);  46. }  47. // Generate a blue curve with Plus symbols,  48. LineItem _myCurve1 = myPane.AddCurve("Sin (theta)",  49. m_pointPairList, Color.Blue, SymbolType.Plus);  50.   51. // Fill the pane background with a color gradient  52. myPane.Fill = new Fill(Color.White, Color.FromArgb(220, 220, 255), 45F);  53.   54. //Make the MajorGrids of Axes visible  55. myPane.XAxis.MajorGrid.IsVisible = true;  56. myPane.YAxis.MajorGrid.IsVisible = true;  57.   58. // Calculate the Axis Scale Ranges  59. zedGraphControl.AxisChange();  60. }  61.   

Page 59: Ejemplo de Acceso a Datos Con Una Base de Access

62. private void Form1_Resize(object sender, EventArgs e)  63. {  64. SetSize();  65. }  66.   67. private void SetSize()  68. {  69. zedGraphControl.Location = new Point(10, 10);  70. // Leave a small margin around the outside of the control  71. zedGraphControl.Size = new Size(this.ClientRectangle.Width - 20,  72. this.ClientRectangle.Height - 20);  73. }  74.   75. private void MyContextMenuBuilder(ZedGraphControl control,  76. ContextMenuStrip menuStrip, Point mousePt,  77. ZedGraphControl.ContextMenuObjectState objState)  78. {  79. // create a new menu item  80. ToolStripMenuItem _item = new ToolStripMenuItem();  81. // This is the user-defined Tag so you can find this menu item later if necessary  82. _item.Name = "Export Data as CSV";  83. _item.Tag = "export_data_csv";  84. // This is the text that will show up in the menu  85. _item.Text = "Export Data as CSV";  86. // Add a handler that will respond when that menu item is selected  87. _item.Click += new System.EventHandler(ShowSaveAsForExportCSV);  88. // Add the menu item to the menu,as 3rd Item  89. menuStrip.Items.Insert(2, _item);  90. }  91.   92. private void ShowSaveAsForExportCSV(object sender, System.EventArgs e)  93. {  94. try  95. {  96. //show saveAs CmdDlg  97. saveFileDialog1.Filter = "CSV files (*.csv)|*.csv";  98. saveFileDialog1.ShowDialog();  99. m_CSVWriter = new StreamWriter(saveFileDialog1.FileName);  100. WriteCSVToStream();  101. m_CSVWriter.Close();  102. MessageBox.Show("CSV File Saved", " ZedGraph ", MessageBoxButtons.OK);  103. }  104. catch (Exception ex)  105. {  106. m_CSVWriter.Close();  107. MessageBox.Show(ex.ToString());  108. }  109. }  110.   111. private void WriteCSVToStream()  112. {  113. //First line is for Headers., X and Y Axis  114. string _xAxisHeader = CheckCSVString(zedGraphControl.GraphPane.XAxis.Ti

tle.Text);  115. string _yAxisHeader = CheckCSVString(zedGraphControl.GraphPane.YAxis.Tit

le.Text);  116. m_CSVWriter.Write(_xAxisHeader + "," + _yAxisHeader + "\n");  117.   118. //subsequent lines are having data  119. for (int i = 0; i < m_pointPairList.Count; i++)  120. {  121. m_CSVWriter.Write(m_pointPairList[i].X + "," + m_pointPairList[i].Y + "\n");  122. }  123. }  124.   125. private string CheckCSVString(string _string)  

Page 60: Ejemplo de Acceso a Datos Con Una Base de Access

126. {//Check to see if there are any characters that can disturb the CSV delimeters.  

127. string _returnString = _string;  128. if (_string.IndexOfAny("\",\x0A\x0D".ToCharArray()) > -1)  129. {  130. _returnString = "\"" + _string.Replace("\"", "\"\"") + "\"";  131. }  132. return _returnString;  133. }  134.   135. }  136. }  

Use the DataSourcePointList to access database dataIt is often desirable to access database data directly by ZedGraph. This saves the trouble of

having to copy and convert the data into a PointPairList class. This is done using

theDataSourcePointList class, which is an IPointList interface type. This means that you can

use a DataSourcePointList in place of a PointPairList when you call

theGraphPane.AddCurve(), GraphPane.AddBar(), etc. methods.

The DataSourcePointList is intended to be very simple to use. All you do is create an instance

of a DataSourcePointList, specify the data source name, and then you specify the column

names in the data table that will be used for each property. The following are the pertinent

properties in the DataSourcePointList:

DataSource 

typically the name of a DataTable containing the data of interest. This can also be an

ArrayList or other data collection type.

XDataMember 

the name of the column in DataSource that will contain the PointPair.X data values

YDataMember 

the name of the column in DataSource that will contain the PointPair.Y data values

ZDataMember 

the name of the column in DataSource that will contain the PointPair.Z data values

TagDataMember 

the name of the column in DataSource that will contain the PointPair.Tag data values

The sample source code below demonstrates the use of these

properties.

For an example, we will use the Northwind database, which is a

sample MS access database. First, you need to link the database

into your Visual Studio 2005 project with the following steps:

Page 61: Ejemplo de Acceso a Datos Con Una Base de Access

1. Right-click on your project in the solution explorer and select

"Add Existing Item..."

2. Set the file type to "Data Files", navigate to the folder that

contains the Northwind.mdb file, select the file and click

"Add"

3. Open up the Tables tree, and check-mark the "Orders" table

4. Leave the dataset name as the default

("NorthwindDataSet")

5. Click "Finish"

You now have a "NorthwindDataSet" class added to your project,

along with a table adapter that will fill a data table with data from the

Orders table.

The following demonstates how to generate a graph from the

database data using the DataSourcePointList. Once the graph is

displayed, you will be able to see a scatter plot showing the freight

cost versus order date. If you mouse-over the individual points, you

will see that the tooltips are sourced from the "ShipName" column of

the data table.

private void CreateGraph_DataSource( ZedGraphControl z1 ){ GraphPane myPane = z1.GraphPane;

// Set the titles myPane.Title.Text = "DataSourcePointList Test"; myPane.XAxis.Title.Text = "Date"; myPane.YAxis.Title.Text = "Freight Charges ($US)";

// Create a new DataSourcePointList to handle the database connection DataSourcePointList dspl = new DataSourcePointList(); // Create a TableAdapter instance to access the database NorthwindDataSetTableAdapters.OrdersTableAdapter adapter = new NorthwindDataSetTableAdapters.OrdersTableAdapter();

Page 62: Ejemplo de Acceso a Datos Con Una Base de Access

// Create a DataTable and fill it with data from the database NorthwindDataSet.OrdersDataTable table = adapter.GetData();

// Specify the table as the data source dspl.DataSource = table; // The X data will come from the "OrderDate" column dspl.XDataMember = "OrderDate"; // The Y data will come from the "Freight" column dspl.YDataMember = "Freight"; // The Z data are not used dspl.ZDataMember = null; // The Tag data will come from the "ShipName" column // (note that this will just set PointPair.Tag = ShipName) dspl.TagDataMember = "ShipName";

// X axis will be dates z1.GraphPane.XAxis.Type = AxisType.Date;

// Make a curve LineItem myCurve = z1.GraphPane.AddCurve( "Orders", dspl, Color.Blue ); // Turn off the line so it's a scatter plot myCurve.Line.IsVisible = false;

// Show the point values. These are derived from the "ShipName" database column, // which is set as the "Tag" property. z1.IsShowPointValues = true;

// Auto set the scale ranges z1.AxisChange();}

Percent Stack Bar DemoNOTE: The code on this page is for ZedGraph version 5. You can view the code for version

4 here.

Page 63: Ejemplo de Acceso a Datos Con Una Base de Access

// Call this method from the Form_Load method, passing your ZedGraphControlpublic void CreateChart( ZedGraphControl zgc ){ GraphPane myPane = zgc.GraphPane;

// Make up some data points string[] quarters = { "Q1-'04", "Q2-'04", "Q3-'04", "Q4-'04" }; double[] y4 = { 20, 15, 90, 70 }; double[] y3 = { 0, 35, 40, 10 }; double[] y2 = { 60, 70, 20, 30 }; double[] y5 = new double[4];

// Set the pane title myPane.Title.Text = "% Product Sales by Quarter by Type"; // Position the legend and fill the background myPane.Legend.Position = LegendPos.TopCenter; myPane.Legend.Fill.Color = Color.LightCyan; // Fill the pane background with a solid color myPane.Fill.Color = Color.Cornsilk; // Fill the axis background with a solid color myPane.Chart.Fill.Type = FillType.Solid; myPane.Chart.Fill.Color = Color.LightCyan; // Set the bar type to percent stack, which makes the bars sum up to 100% myPane.BarSettings.Type = BarType.PercentStack;

Page 64: Ejemplo de Acceso a Datos Con Una Base de Access

// Set the X axis title myPane.XAxis.Title.Text = "Quarter"; myPane.XAxis.Type = AxisType.Text; myPane.XAxis.Scale.TextLabels = quarters;

// Set the Y2 axis properties myPane.Y2Axis.Title.Text = "2004 Total Sales ($M)"; myPane.Y2Axis.IsVisible = true; myPane.Y2Axis.MinorTic.IsOpposite = false; myPane.Y2Axis.MajorTic.IsOpposite = false; myPane.Y2Axis.Scale.FontSpec.FontColor = Color.Red;

// Set the Y axis properties myPane.YAxis.Title.IsVisible = false; myPane.YAxis.Scale.Max = 120; myPane.YAxis.MinorTic.IsOpposite = false; myPane.YAxis.MajorTic.IsOpposite = false; myPane.YAxis.Scale.Format = "0'%'";

// get total values into array for Line for ( int x = 0; x < 4; x++ ) y5[x] = y4[x] + y3[x] + y2[x];

// Add a curve to the graph LineItem curve; curve = myPane.AddCurve( "Total Sales", null, y5, Color.Black, SymbolType.Circle ); // Associate the curve with the Y2 axis curve.IsY2Axis = true; curve.Line.Width = 1.5F; // Make the symbols solid red curve.Line.Color = Color.Red; curve.Symbol.Fill = new Fill( Color.Red ); myPane.Y2Axis.Title.FontSpec.FontColor = Color.Red; curve.Symbol.Size = 8;

// Add a gradient blue bar BarItem bar = myPane.AddBar( "Components", null, y4, Color.RoyalBlue ); bar.Bar.Fill = new Fill( Color.RoyalBlue, Color.White, Color.RoyalBlue );

// Add a gradient green bar bar = myPane.AddBar( "Misc", null, y3, Color.LimeGreen ); bar.Bar.Fill = new Fill( Color.LimeGreen, Color.White, Color.LimeGreen );

// Add a gradient yellow bar bar = myPane.AddBar( "Assemblies", null, y2, Color.Yellow ); bar.Bar.Fill = new Fill( Color.Yellow, Color.White, Color.Yellow );

Page 65: Ejemplo de Acceso a Datos Con Una Base de Access

// Calculate the Axis Scale Ranges zgc.AxisChange();}

Parsing Dates and Times in .NETParsing dates and times using DateTime.Parse and DateTime.ParseExact is simple enough once you know how they work.

It’s simple if you know the format of the string you’re getting and it exactly matches one of the built-in formats, or if you’re willing to let the framework do it’s best to parse the string and you’re ok with it failing otherwise, but if you need to parse specific formats, you’ll need to build your own format specifiers.

There are two ways of parsing date strings: Parse and ParseExact

DateTime.Parse() is the simplest.It tries to figure out the format of the date, and usually does a pretty good job. Here are some examples that work for me, with the result of a DateTime.ToString() on the parsed date:

String to parse Resulting DateTime.ToString01-Jan-2005 1/1/2005 12:00:00 AM01-Jan-2005 12:34 PM 1/1/2005 12:34:00 PM1/1/05 1:3 1/1/2004 1:03:00 AM1 march, 2005 1 am 3/1/2005 1:00:00 AM1995-02-04 2/4/1995 12:00:00 AMFebruary 3 2/3/2005 12:00:00 AM10:30 2/15/2005 10:30:00 AM10 am 2/15/2005 10:00:00 AM

These all did what we expected. DateTime.Parse() is probably the best function to use if the user is typing in a date, and you want it parsed so you can work with it.

If you’re receiving your date strings from data (network, etc), and they’re in a specific format, check this table to see if there’s a predefined format string for your format:

Standard Format Example DateRFC1123 r Sun, 06 Nov 1994 08:49:37 GMTISO 8601 (almost) s 1993-02-14T13:10:30Universal Sortable u

1 2004-04-30 04:30:00Z

If there is, then you can use ParseExact with the single-character format specifier like this:

12

// Parse an RFC1123 date<br />DateTime dt = DateTime.ParseExact(dateString, "r");

Page 66: Ejemplo de Acceso a Datos Con Una Base de Access

There are other strings you can pass to ParseExact, but they’re culture-specific, so generally not all that useful.

In many cases, you have a date string in a specific format,which doesn’t just work with DateTime.Parse. One example is this one, which is allowed by the the ISO 8601 standard, but not parsed by ParseExact when you specify the ‘s’ specifier:

19930214T131030

To parse this, you need to build a string that specifies the format you’re expecting, using characters from this table:

Format specifier Descriptiond, dd, ddd, dddd Current day of the month  d, dd=numeric, ddd=abbreviation (ie, ‘Wed’),

dddd=spelled out.f, ff, fff, ffff, fffff, … Fractions of a second, varying numbers of digitsh, hh Hours, 12 hour format.H, HH Hours, 24 hour formatm, mm MinutesM, MM, MMM, MMMM

Month. MM = 2 digit, MMM = abbreviation (ie, ‘Jan’), MMMM=Spelled out.

s, ss Secondst, tt AM/PM indicator.y, yy, yyyy Yearz, zz, zzz Time zone offset from GMT.: Time separator./ Date separator.Any other character Other characters are matched as literals.

So to parse our sample date, you’d use this string:

12

// Parse an RFC1123 date<br />DateTime dt = DateTime.ParseExact("19930214T131030", "yyyyMMddTHHmmss");

The help covers this stuff fairly well, once you find the documentation. Look for ‘Standard DateTime Format Strings‘ and ‘Custom DateTime Format Strings‘ if you haven’t found what you need here (and let me know, so I can add it).

If you’re receiving strings in a number of formats and you’re not really sure what you’re going to get (like, say, if you’re writing a program that does something with RSS feed data), it’s convenient that you can pass in multiple format specifiers to ParseExact. For example:

12

string[] formats = new string[] { "r", "s", "u", "yyyyMMddTHHmmss" };<br />DateTime dt = DateTime.ParseExact(dateString, formats,<br />   CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);

This is most likely to get you a date you can use.