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

Corregir el error: "Object reference not set to an instance of an object"

Estas en el tema de Corregir el error: "Object reference not set to an instance of an object" en el foro de .NET en Foros del Web. Hola amigos, Tengo una propiedad a la cual necesito llamar desde un hilo, la propiedad se define así: Código: Public Shared Property manejaLabel(ByVal etiquetas() As ...
  #1 (permalink)  
Antiguo 04/10/2006, 04:16
Avatar de SuperPinwi  
Fecha de Ingreso: septiembre-2005
Mensajes: 317
Antigüedad: 18 años, 7 meses
Puntos: 1
Corregir el error: "Object reference not set to an instance of an object"

Hola amigos,

Tengo una propiedad a la cual necesito llamar desde un hilo, la propiedad se define así:

Código:
Public Shared Property manejaLabel(ByVal etiquetas() As Label, ByVal nEtiqueta As Integer) As String
        Get
            Return etiquetas(nEtiqueta).Text
        End Get
        Set(ByVal Value As String)
            MessageBox.Show("Llego hasta aquí")
            etiquetas(nEtiqueta).Text = Value
        End Set
    End Property
donde etiquetas es un array de etiquetas en el que voy guardando diferentes valores y nEtiqueta es el indice del array. (Es de tipo Shared porque lo uso desde un hilo).

Lo tengo que llamar desde un hilo, para que me actualice unas etiquetas que se encuentran en el formulario principal. Para ello tengo este bucle:

Código:
For fila = 0 To n - 1
                    'Asignar a las variables el contenido del registro
                    sNombre = dt.Rows(fila)("nombre").ToString
                    nNumero = dt.Rows(fila)("numero").ToString
                    MessageBox.Show(nNumero.ToString)
                    MessageBox.Show("i" & " :" & i)
                    manejaLabel(etiquetas, i) = nNumero
                    i = i + 1
                    'Como sólo hay 8 etiquetas, cada vez que cargue 8, que vuelva a la primera
                    If (i = 8) Then
                        i = 0
                    End If
                Next
y me salta una excepción con el mensaje: "Object variable or with block variable not set" al hacer esto:
Código:
manejaLabel(etiquetas, i) = nNumero
al definir
Dim etiquetas(8) As Label
etiquetas(0) = Label1
etiquetas(1) = Label2
etiquetas(2) = Label3
etiquetas(3) = Label4
etiquetas(4) = Label5
etiquetas(5) = Label6
etiquetas(6) = Label7
etiquetas(7) = Label8


tras definir el array como
Dim etiquetas(8) As System.Windows.Forms.Label
etiquetas(0) = Label1
etiquetas(1) = Label2
etiquetas(2) = Label3
etiquetas(3) = Label4
etiquetas(4) = Label5
etiquetas(5) = Label6
etiquetas(6) = Label7
etiquetas(7) = Label8
la excepción que salta es otra: "Object reference not set to an instance of an object"

nNumero tiene el valor 55 cuando salta la excepción.
¿Sabéis porqué salta? y cómo corregirlo?

Última edición por SuperPinwi; 04/10/2006 a las 04:59 Razón: cambiar título
  #2 (permalink)  
Antiguo 04/10/2006, 06:51
Avatar de SuperPinwi  
Fecha de Ingreso: septiembre-2005
Mensajes: 317
Antigüedad: 18 años, 7 meses
Puntos: 1
He estado pensando desde hace un rato q tal vez el problema esté en la asignación de referencias. Puesto q asigno a cada posición del array una referencia a una etiqueta, y después a cada posición del array le asigno un número, pero eso realmente quiere decir que la etiqueta se actualiza con el valor del número?? no verdad?? No sé cómo solucionarlo
  #3 (permalink)  
Antiguo 04/10/2006, 07:50
 
Fecha de Ingreso: marzo-2003
Mensajes: 85
Antigüedad: 21 años, 1 mes
Puntos: 1
Pregunta

Hola SuperPinwi,

ese error suele ser típico porque falte por instanciar alguna variable...

Un par de preguntillas, ¿el error te sigue dando en la misma línea? ¿la propiedad manejaLabel, qué está en otra clase diferente a la que tiene el código?
  #4 (permalink)  
Antiguo 05/10/2006, 00:01
Avatar de SuperPinwi  
Fecha de Ingreso: septiembre-2005
Mensajes: 317
Antigüedad: 18 años, 7 meses
Puntos: 1
Cita:
Iniciado por Mitico Ver Mensaje
Hola SuperPinwi,

ese error suele ser típico porque falte por instanciar alguna variable...

Un par de preguntillas, ¿el error te sigue dando en la misma línea? ¿la propiedad manejaLabel, qué está en otra clase diferente a la que tiene el código?
sí, el error salta en la misma línea y tengo todo el código en la misma clase (al principio no lo diseñé así, pero debido a diferentes problemas lo tuve que cambiar).

en principio no parece q falte ninguna variable por instanciar así q no sé q podrá ser en fin a seguir comiéndome el tarro con esto!

Gracias Mitico
  #5 (permalink)  
Antiguo 05/10/2006, 00:31
Avatar de SuperPinwi  
Fecha de Ingreso: septiembre-2005
Mensajes: 317
Antigüedad: 18 años, 7 meses
Puntos: 1
Mitico,

puede ser q tengas razón.

He intentado hacer esto (previa a cualquier instrucción):
Código:
MessageBox.Show(etiquetas(0).ToString)
y salta la misma excepción... puede ser q asigne mal la referencia a las etiquetas??

Saludos y muchas gracias por las molestias
  #6 (permalink)  
Antiguo 05/10/2006, 01:33
 
Fecha de Ingreso: marzo-2003
Mensajes: 85
Antigüedad: 21 años, 1 mes
Puntos: 1
una cosilla con la que me acabo de perder... ¿qué pretendes con éste código que pusiste arriba? es que no lo acabo de ver.

Cita:
Iniciado por SuperPinwi Ver Mensaje
Hola amigos,
Dim etiquetas(8) As System.Windows.Forms.Label
etiquetas(0) = Label1
etiquetas(1) = Label2
etiquetas(2) = Label3
etiquetas(3) = Label4
etiquetas(4) = Label5
etiquetas(5) = Label6
etiquetas(6) = Label7
etiquetas(7) = Label8
  #7 (permalink)  
Antiguo 05/10/2006, 01:39
Avatar de SuperPinwi  
Fecha de Ingreso: septiembre-2005
Mensajes: 317
Antigüedad: 18 años, 7 meses
Puntos: 1
Cita:
Iniciado por Mitico Ver Mensaje
una cosilla con la que me acabo de perder... ¿qué pretendes con éste código que pusiste arriba? es que no lo acabo de ver.

verás, en mi formulario tengo 8 etiquetas en las que voy mostrando varios registros que obtengo de una base de datos.

Guardo esas etiquetas en un array para manipularlas más fácilmente, ya que la base de datos tiene muchos más registros de los q me caben y para recorrer las etiquetas sólo se me ocurría meterlas en un array. Creo q ahí está el error precisamente, en esa asignación.

gracias!
  #8 (permalink)  
Antiguo 05/10/2006, 02:09
 
Fecha de Ingreso: marzo-2003
Mensajes: 85
Antigüedad: 21 años, 1 mes
Puntos: 1
no entiendo muy bien el sentido que tiene hacer eso así, pero si así lo necesitas me parece bien...

no obstante, acabo de hacer la prueba con los pedazos de código que pusiste y me funciona bien... quizá viendo todo el código tuyo descubra algo...
  #9 (permalink)  
Antiguo 05/10/2006, 02:25
Avatar de SuperPinwi  
Fecha de Ingreso: septiembre-2005
Mensajes: 317
Antigüedad: 18 años, 7 meses
Puntos: 1
Aquí tienes el código aunque me acabo de dar cuenta del error... verás, no me permite definir el array como Shared y lo necesito para verlo desde el interior del hilo (y no lo puedo pasar como parámetro porque un hilo no puede llevar parámetros).

si tienes alguna sugerencia te estaré muy agradecida. Lo siento por todas las molestias amigo, ay cada día me veo más torpe con esto

Saludines

Código:
Imports System.Data.OleDb
Imports System
Imports System.Data

Public Class MenuInicial
    Inherits System.Windows.Forms.Form

    Dim ThreadLeerBD
    Dim ThreadActualizaBD

#Region " Código generado por el Diseñador de Windows Forms "

    Public Sub New()
        MyBase.New()

        'El Diseñador de Windows Forms requiere esta llamada.
        InitializeComponent()

        'Agregar cualquier inicialización después de la llamada a InitializeComponent()

    End Sub

    'Form reemplaza a Dispose para limpiar la lista de componentes.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Requerido por el Diseñador de Windows Forms
    Private components As System.ComponentModel.IContainer

    'NOTA: el Diseñador de Windows Forms requiere el siguiente procedimiento
    'Puede modificarse utilizando el Diseñador de Windows Forms. 
    'No lo modifique con el editor de código.
    Friend Shared WithEvents Label1 As New System.Windows.Forms.Label
    ...
    Friend Shared WithEvents Label8 As New System.Windows.Forms.Label
    Friend WithEvents BLeerBD As System.Windows.Forms.Button
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.Label1 = New System.Windows.Forms.Label
        ...
        Me.Label8 = New System.Windows.Forms.Label
        Me.BLeerBD = New System.Windows.Forms.Button
        Me.TxtBxPorcentaje = New System.Windows.Forms.TextBox
        Me.SuspendLayout()
        '
        'Label1
        '
        Me.Label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label1.Location = New System.Drawing.Point(32, 40)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(128, 23)
        Me.Label1.TabIndex = 0
        Me.Label1.Text = "Label1"
        '
        ...
        'Label8
        '
        Me.Label8.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label8.ForeColor = System.Drawing.SystemColors.HotTrack
        Me.Label8.Location = New System.Drawing.Point(32, 376)
        Me.Label8.Name = "Label8"
        Me.Label8.Size = New System.Drawing.Size(128, 24)
        Me.Label8.TabIndex = 7
        Me.Label8.Text = "Label8"
        '
        '
        'BLeerBD
        '
        Me.BLeerBD.BackColor = System.Drawing.SystemColors.InactiveCaption
        Me.BLeerBD.ForeColor = System.Drawing.SystemColors.ControlLightLight
        Me.BLeerBD.Location = New System.Drawing.Point(320, 104)
        Me.BLeerBD.Name = "BLeerBD"
        Me.BLeerBD.Size = New System.Drawing.Size(75, 40)
        Me.BLeerBD.TabIndex = 8
        Me.BLeerBD.Text = "Leer Base De Datos"
        '
        'BActualizarBD
        '
        Me.BActualizarBD.BackColor = System.Drawing.SystemColors.InactiveCaption
        Me.BActualizarBD.ForeColor = System.Drawing.SystemColors.ControlLightLight
        Me.BActualizarBD.Location = New System.Drawing.Point(320, 256)
        Me.BActualizarBD.Name = "BActualizarBD"
        Me.BActualizarBD.Size = New System.Drawing.Size(80, 48)
        Me.BActualizarBD.TabIndex = 9
        Me.BActualizarBD.Text = "Actualizar Base de Datos"
        '
        'MenuInicial
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.BackColor = System.Drawing.SystemColors.InactiveCaptionText
        Me.ClientSize = New System.Drawing.Size(424, 430)
        Me.Controls.Add(Me.TxtBxPorcentaje)
        Me.Controls.Add(Me.BActualizarBD)
        Me.Controls.Add(Me.BLeerBD)
        Me.Controls.Add(Me.Label8)
        ...
        Me.Controls.Add(Me.Label1)
        Me.Menu = Me.MainMenu1
        Me.Name = "MenuInicial"
        Me.Text = "Aplicación Hilos y Bases de Datos"
        Me.ResumeLayout(False)

        Dim etiquetas(8) As System.Windows.Forms.Label
        'asignamos una etiqueta por cada posición del array
        etiquetas(0) = Label1
        etiquetas(1) = Label2
        etiquetas(2) = Label3
        etiquetas(3) = Label4
        etiquetas(4) = Label5
        etiquetas(5) = Label6
        etiquetas(6) = Label7
        etiquetas(7) = Label8

    End Sub

#End Region

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub

    Public Shared Property manejaLabel(ByVal etiquetas() As System.Windows.Forms.Label, ByVal nEtiqueta As Integer) As String
        Get
            Return etiquetas(nEtiqueta).Text
        End Get
        Set(ByVal Value As String)
            MessageBox.Show("Llego hasta aquí")
            etiquetas(nEtiqueta).Text = Value
        End Set
    End Property

    Private Sub BLeerBD_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BLeerBD.Click
        ThreadLeerBD = New System.Threading.Thread(AddressOf Me.EjecutaHiloBD)
        ThreadLeerBD.start()
        ThreadLeerBD.isBackGround = True
    End Sub

    'HILO LEE BASE DE DATOS
    'descripción: se encarga de leer una base de datos y mostrar por 
    'pantalla en la interfaz principal los valores que de ella obtiene.
    Public Shared Sub EjecutaHiloBD()
        'Crea la conexión
        Dim objConn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\Super.Pinwi\Mis documentos\Mis bases de datos\numeros\numeros.mdb")
        Dim objAcciones As New OleDbCommand
        Dim dt As DataTable
        Dim objAdapter
        Dim i As Integer
        Dim fila As Integer
        Dim n As Integer
        Dim sNombre As String
        Dim nNumero As Integer
        Dim FormMostrar
        Dim menu As New MenuInicial
        Dim prueba As Integer

        Try
            'Se abre la conexión de la base de datos
            objConn.Open()
            'Se escogen los registros de la base de datos que se desean
            objAdapter = New OleDbDataAdapter("SELECT * FROM numeros ORDER BY numero", objConn)
            'Se almacena la base de datos en el dataTable
            dt = New DataTable
            objAdapter.Fill(dt)
            'Se almacena en n el número de filas de la base de datos
            n = dt.Rows.Count
            'Se asocia la conexión con el objeto acciones
            objAcciones.Connection = objConn
            MessageBox.Show("a ve q tiene etiquetas")
            'MessageBox.Show(etiquetas(0).Text)
            If n = 0 Then
                MessageBox.Show("No se ha encontrado ningún registro que coincida con la selección")
            Else
                'Recorre las filas en el dataTable y las va asignando a las etiquetas
                'del formulario principal para que se muestren
                For fila = 0 To n - 1
                    sNombre = dt.Rows(fila)("nombre").ToString
                    nNumero = dt.Rows(fila)("numero").ToString
                    MessageBox.Show(nNumero.ToString)
                    MessageBox.Show("i" & " :" & i)
                    manejaLabel(etiquetas, i) = nNumero
                    i = i + 1
                    'Como sólo hay 8 etiquetas, cada vez que cargue 8, que vuelva a la primera
                    If (i = 8) Then
                        i = 0
                    End If
                Next
            End If
            objConn.Close()
        Catch ex As Exception
            MessageBox.Show(Err.Description, "Información del sistema")
        End Try
    End Sub
End Class
  #10 (permalink)  
Antiguo 05/10/2006, 02:55
 
Fecha de Ingreso: marzo-2003
Mensajes: 85
Antigüedad: 21 años, 1 mes
Puntos: 1
Creo que efectivamente, ahí tienes el problema, estás definiendo el array como local dentro del proceso "InitializeComponent". Aunque sí lo inicialices y asignes cada Label al elemento del array en ese punto define el array al principio.

No te debería hacer falta ni ponerlo como Shared, simplemente con definirlo a nivel de la clase debería ser suficiente:

Código:
Dim ThreadLeerBD
Dim ThreadActualizaBD

Private etiquetas(8) As System.Windows.Forms.Label

#Region " Código generado por el Diseñador de Windows Forms "

    Public Sub New()
        MyBase.New()
    .....
    .....
Espero que haya suerte y eso te sirva.
  #11 (permalink)  
Antiguo 05/10/2006, 03:01
Avatar de SuperPinwi  
Fecha de Ingreso: septiembre-2005
Mensajes: 317
Antigüedad: 18 años, 7 meses
Puntos: 1
efectivamente ahí estaba el error, muchísimas gracias por todo amigo
ahora al menos guarda los valores en el array aunque todavía no los muestra en el formulario
algún día te invitaré a algo por todas las molestias jeje
  #12 (permalink)  
Antiguo 05/10/2006, 06:50
Avatar de SuperPinwi  
Fecha de Ingreso: septiembre-2005
Mensajes: 317
Antigüedad: 18 años, 7 meses
Puntos: 1
ale ya ta resuelto jejeje he puesto las variables label de la misma forma y ya funciona perfectamente aunque cada vez q añado algún control en el formulario o algo me quita las declaraciones de ahí y las devuelve donde estaban, lo cual es un poco rollo, pero bueno por lo menos ya puedo actualizar el formulario que ya es algo jejeje.

Miles de gracias Mitico!!
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

SíEste tema le ha gustado a 1 personas (incluyéndote)




La zona horaria es GMT -6. Ahora son las 11:15.