Foros del Web » Programación para mayores de 30 ;) » .NET »

Mostrar datos en tiempo real en DataGridview

Estas en el tema de Mostrar datos en tiempo real en DataGridview en el foro de .NET en Foros del Web. Hola estoy hasta la madre de darle vueltas al asunto asi que recurriré a los expertos Tengo aplicación 1 que monitoría unas maquinas de SMT ...
  #1 (permalink)  
Antiguo 31/08/2010, 19:02
 
Fecha de Ingreso: julio-2008
Mensajes: 26
Antigüedad: 15 años, 9 meses
Puntos: 0
Mostrar datos en tiempo real en DataGridview

Hola estoy hasta la madre de darle vueltas al asunto asi que recurriré a los expertos

Tengo aplicación 1 que monitoría unas maquinas de SMT y guarda en BD los errores causados.

Tengo otra aplicación que necesita mostrar lo que la aplicación 1 está guardando, el grid se tiene que estar refrescando todo el tiempo, cada instante o cada 10 segundos no importa pero son muchos refresh

Cree un Thread que se la pasa haciendo la consulta y asignando resultados al datagridview por medio de un bindingsource

Si lo hace 1 ves, lo hace bien, lo hace 2, 3, 4.... N pero de repente de la nada sale este error


Código:
private BindingSource4 = New BindingSource()
sub algo()
Try
	ds4 = New DataSet
	da4 = New SqlDataAdapter(q4, c_grid)
	da4.FillSchema(ds4, SchemaType.Source, "ref")
	da4.Fill(ds4, "ref")
	'BindingSource4 = New BindingSource()
	BindingSource4.DataSource = ds4
	BindingSource4.DataMember = "ref"
	Try
		DataGridView4.DataSource = BindingSource4
	Catch ex As Exception
		Debug.Print(ex.Message)
	Finally
		DataGridView4.Refresh()
	End Try
Catch ex As Exception
	Debug.Print(ex.Message)                            
Finally
'nada
End Try
end sub
ya puse los BindingSource como objetos en la forma, ya los declaré como DIM, PUBLIC, PRIVATE y ocurre lo mismo, utilize un DATAVIEW sencillo y ocurrió igual, y como estoy a punto de volverme loca necesito muuucho de su apoyo

AYUDA!!!!!
  #2 (permalink)  
Antiguo 31/08/2010, 19:25
Avatar de xjuanch0x  
Fecha de Ingreso: septiembre-2009
Mensajes: 125
Antigüedad: 14 años, 7 meses
Puntos: 1
Respuesta: Mostrar datos en tiempo real en DataGridview

Cita:
Iniciado por altairax Ver Mensaje
Hola estoy hasta la madre de darle vueltas al asunto asi que recurriré a los expertos

Tengo aplicación 1 que monitoría unas maquinas de SMT y guarda en BD los errores causados.

Tengo otra aplicación que necesita mostrar lo que la aplicación 1 está guardando, el grid se tiene que estar refrescando todo el tiempo, cada instante o cada 10 segundos no importa pero son muchos refresh

Cree un Thread que se la pasa haciendo la consulta y asignando resultados al datagridview por medio de un bindingsource

Si lo hace 1 ves, lo hace bien, lo hace 2, 3, 4.... N pero de repente de la nada sale este error




Código:
private BindingSource4 = New BindingSource()
sub algo()
Try
	ds4 = New DataSet
	da4 = New SqlDataAdapter(q4, c_grid)
	da4.FillSchema(ds4, SchemaType.Source, "ref")
	da4.Fill(ds4, "ref")
	'BindingSource4 = New BindingSource()
	BindingSource4.DataSource = ds4
	BindingSource4.DataMember = "ref"
	Try
		DataGridView4.DataSource = BindingSource4
	Catch ex As Exception
		Debug.Print(ex.Message)
	Finally
		DataGridView4.Refresh()
	End Try
Catch ex As Exception
	Debug.Print(ex.Message)                            
Finally
'nada
End Try
end sub
ya puse los BindingSource como objetos en la forma, ya los declaré como DIM, PUBLIC, PRIVATE y ocurre lo mismo, utilize un DATAVIEW sencillo y ocurrió igual, y como estoy a punto de volverme loca necesito muuucho de su apoyo

AYUDA!!!!!

Muestra el código de tu Hilo
__________________
Juan David Torres Vasquez
[email protected]
Microsoft Certified Technology Specialist (MCTS)
DCE Platinum en Visual C# y VB.NET
  #3 (permalink)  
Antiguo 31/08/2010, 20:05
 
Fecha de Ingreso: marzo-2010
Mensajes: 38
Antigüedad: 14 años, 1 mes
Puntos: 0
Respuesta: Mostrar datos en tiempo real en DataGridview

Estás cerrando la conexiones?
  #4 (permalink)  
Antiguo 01/09/2010, 08:07
 
Fecha de Ingreso: julio-2008
Mensajes: 26
Antigüedad: 15 años, 9 meses
Puntos: 0
Respuesta: Mostrar datos en tiempo real en DataGridview

este es el código
Código:
Sub ciclico()
        Try
            hilo = New Thread(New ThreadStart(AddressOf actualizar_grids))
            If hilo.IsAlive = False Then
                hilo.Start()
            End If
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
    End Sub

 Sub actualizar_grids()
        If TextBox1.Text <> "" Then
            MODEL = TextBox1.Text
            Try
                Dim dr As SqlDataReader
                Dim cmdDB As SqlCommand
                q0 = "select max(HORA_INSERCION) as HORA_INSERCION , model from TAB_EVENTDATA_2 WHERE id_tab_files = " & Me.lb_id.Text & " group by model"
                If c_grid.State = ConnectionState.Closed Then
                    c_grid.ConnectionString = My.Settings.cadena_conexion
                    c_grid.Open()
                End If
                If c_grid.State = ConnectionState.Open Then
                    cmdDB = New SqlCommand(q0, c_grid)
                    dr = cmdDB.ExecuteReader
                    If dr.Read Then
                        hora = dr.GetValue(0).ToString
                        new_model = dr.GetValue(1).ToString
                        dr.Close()
                        If MODEL = new_model Then
                            Try
                                q1 = "select ..."
                                q2 = "select ..."
                                q3 = "select ..."
                                q4 = "select ..."
                                If c_grid.State = ConnectionState.Open Then
                                    Control.CheckForIllegalCrossThreadCalls = False
                                    Try
                                        ds1 = New DataSet
                                        da1 = New SqlDataAdapter(q1, c_grid)
                                        da1.FillSchema(ds1, SchemaType.Source, "error_code")
                                        da1.Fill(ds1, "error_code")
                                        'BindingSource1 = New BindingSource()
                                        BindingSource1.DataSource = ds1
                                        BindingSource1.DataMember = "error_code"
                                        Try
                                            DataGridView1.DataSource = BindingSource1
                                        Catch ex As Exception
                                            Debug.Print(ex.Message)
                                        Finally
                                            DataGridView1.Refresh()
                                        End Try
                                    Catch ex As Exception
                                        Debug.Print(ex.Message)
                                    Finally

                                    End Try
                                    Try
                                        ds2 = New DataSet
                                        da2 = New SqlDataAdapter(q2, c_grid)
                                        da2.FillSchema(ds2, SchemaType.Source, "Feeder")
                                        da2.Fill(ds2, "Feeder")
                                        'BindingSource2 = New BindingSource()
                                        BindingSource2.DataSource = ds2
                                        BindingSource2.DataMember = "Feeder"
                                        Try
                                            DataGridView2.DataSource = BindingSource2
                                        Catch ex As Exception
                                            Debug.Print(ex.Message)
                                        Finally
                                            DataGridView2.Refresh()
                                        End Try
                                    Catch ex As Exception
                                        Debug.Print(ex.Message)
                                    Finally

                                    End Try
                                    Try
                                        ds3 = New DataSet
                                        da3 = New SqlDataAdapter(q3, c_grid)
                                        da3.FillSchema(ds3, SchemaType.Source, "Nozzle")
                                        da3.Fill(ds3, "Nozzle")
                                        'BindingSource3 = New BindingSource()
                                        BindingSource3.DataSource = ds3
                                        BindingSource3.DataMember = "Nozzle"
                                        Try
                                            DataGridView3.DataSource = BindingSource3
                                        Catch ex As Exception
                                            Debug.Print(ex.Message)
                                        Finally
                                            DataGridView3.Refresh()
                                        End Try
                                    Catch ex As Exception
                                        Debug.Print(ex.Message)
                                    Finally

                                    End Try

                                    Try
                                        ds4 = New DataSet
                                        da4 = New SqlDataAdapter(q4, c_grid)
                                        da4.FillSchema(ds4, SchemaType.Source, "ref")
                                        da4.Fill(ds4, "ref")
                                        'BindingSource4 = New BindingSource()
                                        BindingSource4.DataSource = ds4
                                        BindingSource4.DataMember = "ref"
                                        Try
                                            DataGridView4.DataSource = BindingSource4
                                        Catch ex As Exception
                                            Debug.Print(ex.Message)
                                        Finally
                                            DataGridView4.Refresh()
                                        End Try
                                    Catch ex As Exception
                                        Debug.Print(ex.Message)
                                    Finally

                                    End Try
                                End If
                            Catch ex As Exception
                                Debug.Print(ex.Message)
                            Finally

                            End Try
                        Else
                            'no son iguales generar reporte
                            Me.TextBox1.Text = new_model
                        End If
                    Else
                        Control.CheckForIllegalCrossThreadCalls = False
                        Me.TextBox1.Text = ""
                        Me.TextBox1.Visible = False
                        DataGridView1.DataSource = Nothing
                        DataGridView2.DataSource = Nothing
                        DataGridView3.DataSource = Nothing
                        DataGridView4.DataSource = Nothing

                        DataGridView1.Refresh()
                        DataGridView2.Refresh()
                        DataGridView3.Refresh()
                        DataGridView4.Refresh()
                    End If
                    c_grid.Close()
                End If
            Catch ex As Exception
                Debug.Print(ex.Message)
            Finally

            End Try
            Try
                Application.DoEvents()
                System.Threading.Thread.Sleep(20000) ' Sleep for 20 second
            Catch ex As Exception
                Debug.Print(ex.Message)
            Finally
                ciclico()
            End Try
        End If
    End Sub
  #5 (permalink)  
Antiguo 02/09/2010, 15:58
 
Fecha de Ingreso: julio-2008
Mensajes: 26
Antigüedad: 15 años, 9 meses
Puntos: 0
Respuesta: Mostrar datos en tiempo real en DataGridview

ayuda por favoooor!!!
  #6 (permalink)  
Antiguo 12/09/2010, 03:38
 
Fecha de Ingreso: marzo-2007
Mensajes: 74
Antigüedad: 17 años, 1 mes
Puntos: 0
Respuesta: Mostrar datos en tiempo real en DataGridview otra forma

Crea otro programa para que lo pruebes

paso #1

Copiate este codigo y agregra un Datagridview a la forma
yo lo tengo en modulo1.vb para solo hacer una vez el diseno.



Mensaje_Error pon lo que tu quiera.




Public Sub Muestra_DVG(ByVal DGV As DataGridView, ByVal Tabla As String, ByVal Instruccion As String)
Try
Dim conn As SqlClient.SqlConnection
conn = New SqlClient.SqlConnection(SerVer)
Dim DA As SqlClient.SqlDataAdapter
DA = New SqlClient.SqlDataAdapter(Instruccion, conn)
' crear conjunto de datos
Dim DS As DataSet
DS = New DataSet

Dim dt As DataTable = New DataTable(Tabla)
DA.Fill(DS)
DGV.DataSource = DS.Tables(0)

DGV.ColumnHeadersDefaultCellStyle.Font = New Font("Tahoma", 9, FontStyle.Bold, GraphicsUnit.Point)
DGV.ColumnHeadersDefaultCellStyle.BackColor = SystemColors.ControlDark
DGV.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single
DGV.DefaultCellStyle.Font = New Font("Tahoma", 8, FontStyle.Regular, GraphicsUnit.Point)
DGV.DefaultCellStyle.BackColor = Color.Empty
DGV.AlternatingRowsDefaultCellStyle.BackColor = Color.LightGoldenrodYellow
DGV.CellBorderStyle = DataGridViewCellBorderStyle.Single
DGV.GridColor = SystemColors.ControlDarkDark

DGV.AutoResizeColumns(DataGridViewAutoSizeColumnsM ode.AllCells)
DGV.AllowUserToAddRows = False

Catch ex As Exception
Mensaje_Error("datagrid ", Err.Number, Err.Description)
End Try
End Sub



Paso #2

hacer tu consulta
(con estas 2 lineas ya puedes crear cualquier datagrid)




private Sub Carga_Reloj()

q0 = "select max(HORA_INSERCION) as HORA_INSERCION , model from TAB_EVENTDATA_2 WHERE id_tab_files = " & Me.lb_id.Text & " group by model"

Muestra_DVG(DataGridView1, "TAB_EVENTDATA_2", q0 )
End Sub



Paso #3
poner el evento del timer

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Carga_Reloj()
End Sub




Private Sub FrmReloj_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

SerVer = "Data Source=.\SQLEXPRESS;AttachDbFilename=c:\x.mdf;Inte grated Security=True;Connect Timeout=30;User Instance=True"
Carga_Reloj()

Timer1.Enabled = True
Timer1.Interval = 1000
End Sub


Yo lo tengo para recordarme mis llamadas que tengo que hacer y me funciona muy bien

En el formulario pones un control timer tambien



Espero te sirva.
saludos
Fernando.
  #7 (permalink)  
Antiguo 14/09/2010, 11:03
 
Fecha de Ingreso: julio-2008
Mensajes: 26
Antigüedad: 15 años, 9 meses
Puntos: 0
Respuesta: Mostrar datos en tiempo real en DataGridview otra forma

Cita:
Iniciado por winexim Ver Mensaje
Espero te sirva.
saludos
Fernando.
Fernando
en cuando terminen de arreglarme mi outlook lo implemento y te cuento
Gracias
  #8 (permalink)  
Antiguo 14/09/2010, 16:43
 
Fecha de Ingreso: marzo-2007
Mensajes: 74
Antigüedad: 17 años, 1 mes
Puntos: 0
Respuesta: Mostrar datos en tiempo real en DataGridview

En el timer tambien pudes poner que te mande desplegar el
datagridview de nuevo cada vez que cambie el numero de registros.
o una sumatoria de datos.
  #9 (permalink)  
Antiguo 22/09/2010, 09:33
 
Fecha de Ingreso: julio-2008
Mensajes: 26
Antigüedad: 15 años, 9 meses
Puntos: 0
Respuesta: Mostrar datos en tiempo real en DataGridview

winexim,
muchas gracias, funciona perfecto =)
Que éxito!!!

Etiquetas: bindingsource, datagridview, hilos
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 05:49.