Visual Basic - Leer de un Datagrid

Life is soft - evento anual de software empresarial
 
Vista:
sin imagen de perfil

Leer de un Datagrid

Publicado por Alberto (5 intervenciones) el 27/11/2013 17:32:04
Hola muy buenas.

A ver si me podeis hechar una mano. Quiero acceder a un Datagrid para leer alguno de sus valores. Este datagrid lo formo de la siguiente manera.

Leo mi base de datos (SQL) y en función de la busqueda que haga, filtro y coloco el resultado en el datagrid. Luego quiero acudir al datagrid para recoger los valores y generar un pdf.

El datagrid me lo genera perfectamente el problema viene al leerlo que me da este error:

"El índice estaba fuera del intervalo. Debe ser un valor no negativo e inferior al tamaño de la colección.
Nombre del parámetro: index"

¿Alguien sabe que esta ocurriendo?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
Dim cn As OleDbConnection
    Dim cmd As OleDbCommand
    Dim reader As OleDbDataReader
    Dim Rw As DataRow 'creamos una fila
    Dim TblDet As New DataTable("Detalle") 'Creamos una Tabla  temporal con su nombre
    Dim Ds As New DataSet()
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        cn = New OleDbConnection()
        cn.ConnectionString = ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Joaquin\Documents\NWINDVBP.mdb;User Id=admin;Password=;")
        Try
            TblDet = Ds.Tables.Add
            With TblDet.Columns
                .Add("CustomerID", Type.GetType("System.String"))
                .Add("CompanyNaml", Type.GetType("System.String"))
                .Add("ContactName", Type.GetType("System.String"))
                .Add(" City", Type.GetType("System.String"))
            End With
            'Agregamos una Clave Principal a la Tabla Dinamica 
            'para que no se repìtan los registros 
            With Ds.Tables(0)
                .PrimaryKey = New DataColumn() {.Columns("id")}
            End With
            '___________________________________________
            cn.Open()
            'MsgBox("Conexión Abierta")
            cmd = New OleDbCommand()
            cmd.Connection = cn
            cmd.CommandText = "SELECT CustomerID, CompanyName, ContactName, City FROM Customers"
            reader = cmd.ExecuteReader()
            While reader.Read
                If (reader("City") = TextBox1.Text) Then
                    'aqui agrego la tabla temporal al dataGrid en el dataSource----
                    DataGridView2.DataSource = TblDet
                    Rw = TblDet.NewRow() 'le decimos que crearemos una nueva fila
                    'se agregan los N cantidad de registros asi sucesivamente
                    Rw(0) = reader("CustomerID").ToString()
                    Rw(1) = reader("CompanyName")
                    Rw(2) = reader("ContactName")
                    Try
                        TblDet.Rows.Add(Rw)
                        TblDet.AcceptChanges()
                    Catch
                        MsgBox("Articulo repetido bla bla bla")
                    End Try
                End If
            End While
        Catch ex As Exception
            MsgBox("Error al realizar la conexión: " & ex.Message)
        End Try
        'Leo el datagrid
        Dim Registro As String
        Registro = DataGridView2.SelectedRows(0).Cells(0).Value
        MsgBox(Registro)
        If cn.State = ConnectionState.Open Then cn.Close()
End Sub
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

Leer de un Datagrid

Publicado por omar (17 intervenciones) el 27/11/2013 17:41:00
Saludos

Podria ayudarte pero con dataset

Es fácil leer desde ahí

usas mucho código para hacer algo

envíame un email

pc.net.2018 en hotmail
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Leer de un Datagrid

Publicado por Alberto (5 intervenciones) el 27/11/2013 17:52:41
Hola Omar.

Justo ahora lo he conseguido.
El codigo que leía de un datagrid era este trocito.

1
2
3
Dim Registro As String
Registro = DataGridView2.SelectedRows(0).Cells(0).Value
MsgBox(Registro)

Ahora he cambiado esa instrucción por la siguiente y parece funcionar, de todas formas si tengo alguna duda te escribo un correo.

1
2
Dim Registro As String
Registro = DataGridView2.Item(0, 1).Value

Muchas gracias por contestar.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar