Visual Basic.NET - la conversión del tipo 'dbnull' en el tipo 'string' no es válida

 
Vista:
sin imagen de perfil

la conversión del tipo 'dbnull' en el tipo 'string' no es válida

Publicado por pabnoc (11 intervenciones) el 13/12/2016 11:04:14
EL ERROR EN ......

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
Private Sub Guardar_Click(sender As Object, e As EventArgs) Handles Guardar.Click
        Conexión1.ConnectionString = connString
        Conexión1.Open()
        '
        Dim row As DataGridViewRow = DGV.CurrentRow
        Dim str As String
 
        'Si buscamos por la clave
 
        If ComboBox1.Text = "Clave" Then
 
        End If
 
 
 
        str = "update [Sujeto] set [Nombres] = '" & CStr(row.Cells("Nombres").Value) & _
                            "' , [medidas] = '" & CStr(row.Cells("medidas").Value) & _
                                            "', [peso] = '" & CStr(row.Cells("peso").Value) & _
                                                            "', [long] = '" & CStr(row.Cells("long").Value) & _
                                                                            "', [sup] = '" & CStr(row.Cells("sup").Value) & _
                                                                                            "', [corp] = '" & CStr(row.Cells("corp").Value) & _
                                                                                                            "', [kam] = '" & CStr(row.Cells("kam").Value) & _
                                                                                                                            "', [prom] = '" & CStr(row.Cells("prom").Value) & _
                                                                                                                                            "', [manr] = '" & CStr(row.Cells("manr").Value) & _
                                                                                                                                                            "', [bau] = '" & CStr(row.Cells("bau").Value) & _
                                                                                                                                                                            "', [madd] = '" & CStr(row.Cells("madd").Value) & _
                                                                                                                                                                                            "', [peris] = '" & CStr(row.Cells("peris").Value) & _
                                                                                                                                                                                                            "', [fecha] = '" & CStr(row.Cells("fecha").Value) & "' Where [Clave] = '" & TextBox1.Text & "'"


MUCHAS GRACIAS CHICOS
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
sin imagen de perfil
Val: 481
Bronce
Ha mantenido su posición en Visual Basic.NET (en relación al último mes)
Gráfica de Visual Basic.NET

la conversión del tipo 'dbnull' en el tipo 'string' no es válida

Publicado por Miguel (476 intervenciones) el 13/12/2016 19:50:52
En lugar de la función "CStr" utiliza una función propia (verificando antes de convertir si el valor es tipo DBNull), ya que tienes datos vacíos (puede ser en cualquier columna/campo).

Saludos
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

la conversión del tipo 'dbnull' en el tipo 'string' no es válida

Publicado por pabnoc (11 intervenciones) el 13/12/2016 22:28:23
gracias probando.....
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

la conversión del tipo 'dbnull' en el tipo 'string' no es válida

Publicado por pabnoc (11 intervenciones) el 13/12/2016 22:54:03
un ejemplo de como ??? ... por favor
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

ayuda no coinciden los tipos de datos en la expresión de criterios

Publicado por pabnoc (11 intervenciones) el 13/12/2016 23:11:18
solucionado!!! cambie cstr por convert.tostring.....ahora tira error no coinciden los tipos de datos en la expresión de criterios !!!!
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
Option Explicit On
Option Strict On
'importamos la libreia  Microsoft Access 14.0 library
'Imports Access = Microsoft.Office.Interop.Access
Imports System.Data
Imports System.Data.OleDb
Imports System.IO
Imports System.Windows.Forms
 
 
 
Public Class Archivos
    'La conexión
    Dim connString As String = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" _
                               & "D:\BASE DATOS\Access y System.OleDb en VB.NET 2012\Carpeta\Mi_base.accdb" & ";Persist Security Info=False;") 'CAMBIA LA RUTA
 
    Dim Conexión1 As OleDbConnection = New OleDbConnection
    'para buscar
    Public dr As OleDbDataReader
 
    'Para el DataGribView(DGV) en inicio
    Dim ds As DataSet = New DataSet
    Dim Oda As OleDbDataAdapter
    Dim tables As DataTableCollection = ds.Tables
 
    Dim ruta As String = "D:\BASE DATOS\Access y System.OleDb en VB.NET 2012\Carpeta\Mi_base.accdb" 'CAMBIA LA RUTA
    Dim Nombre As String
    Dim a As Boolean = True, b As Boolean = False
 
 
    'Sub para cargar los datos en el DataGribView
    Sub cargar()
        Try
            'Conectamos y abrimos
            Conexión1.ConnectionString = connString
            Conexión1.Open()
 
            ds = New DataSet
            Dim table As DataTableCollection = ds.Tables
 
            Oda = New OleDbDataAdapter("Select [Clave], [Nombres], [medidas], [peso], [long], [sup], [corp], [kam], [prom], [manr], [bau], [madd], [peris], [fecha] from Sujeto", Conexión1)
            Oda.Fill(ds, "Sujeto")
            'Asignamos
            DGV.DataSource = New DataView(table(0))
            DGV.Columns(1).Width = 180 'Aumentamos el ancho de la columna Nombres
            DGV.Refresh()
            'Liberamos
            ds.Dispose()
            Oda.Dispose()
            Conexión1.Close() 'Cerramos
 
        Catch ex As Exception
            ex.Message.ToUpper()
        End Try
    End Sub
 
    'Habilitar controles según los registros
    Sub comprueba()
        If DGV.Rows.Count > -1 Then
            TextBox1.Enabled = True
            ComboBox1.Enabled = True
            Buscar.Enabled = True
            Editar.Enabled = False
            Guardar.Enabled = False
            Eliminar.Enabled = False
            Registrar.Enabled = True
            Label4.Text = "Al buscar y encontrar el registro, puedes editar todo, excepto la Clave."
        End If
 
        If DGV.Rows.Count < 1 Then
            TextBox1.Enabled = False
            ComboBox1.Enabled = False
            Buscar.Enabled = False
            Editar.Enabled = False
            Guardar.Enabled = False
            Eliminar.Enabled = False
            Registrar.Enabled = True
            Label4.Text = "Registre información"
        End If
    End Sub
    'Habilita controles
    Sub habilita()
        DGV.ReadOnly = True
        Editar.Text = "Editar"
        Editar.Enabled = False
        Guardar.Enabled = False
        Buscar.Enabled = True
        Eliminar.Enabled = False
        Registrar.Enabled = True
        TextBox1.Enabled = True
        TextBox1.Text = ""
        ComboBox1.Enabled = True
    End Sub
 
    'El dataset
    Sub Datas()
        With ds.Tables("Sujeto")
            'Indicar en la propiedad Sort el campo por el cual buscar  
            .DefaultView.Sort = "Clave"
            'Asignar el origen de datos a la grilla  
            DGV.DataSource = .DefaultView
        End With
    End Sub
    'Actualizar
    Sub Actualizar()
        ds.Clear()
        DGV.Refresh()
        cargar()
        Datas()
        comprueba()
        TextBox1.Text = ""
        ComboBox1.Text = "Clave"
    End Sub
 
 
    'Si cerramos
    Private Sub Archivos_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        Registro.Show()
    End Sub
    'Cofig.. de inicio
    Private Sub Archivos_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'TODO: esta línea de código carga datos en la tabla 'Mi_baseDataSet.Sujeto' Puede moverla o quitarla según sea necesario.
        Me.SujetoTableAdapter.Fill(Me.Mi_baseDataSet.Sujeto)
        Try
            Me.CenterToScreen()
            ComboBox1.Text = "Clave"
            'Llenamos el DGV
            cargar()
            comprueba()
 
            With DGV
                .ReadOnly = True
                'Para seleccionar todo, pero en este caso solo la fila a buscar
                .SelectionMode = DataGridViewSelectionMode.FullRowSelect
                .MultiSelect = False
                'Evitamos que se agregue la última fila(Fila vacía)
                .AllowUserToAddRows = False
            End With
 
            Datas()
 
        Catch ex As Exception
            ex.Message.ToUpper()
        End Try
    End Sub
 
 
 
    'Buscamos el registro y nos posicionamos en la fila correspondiente en el Dgv 
    Private Sub Buscar_Click(sender As Object, e As EventArgs) Handles Buscar.Click
        Try
            If TextBox1.Text = "" Then Exit Sub
            If DGV.Rows.Count < 1 Then Exit Sub
 
            With ds.Tables("Sujeto")
 
                'Buscamos por la Clave
                If ComboBox1.Text = "Clave" Then
                    .DefaultView.Sort = "Clave"
                    If DGV.Rows.Count > 0 Then
                        Label4.Text = "Al buscar y encontrar el registro, puedes editar todo, excepto la Clave."
                    End If
                End If
                'Buscamos por los nombres
                If ComboBox1.Text = "Nombres" Then
                    .DefaultView.Sort = "Nombres"
                    If DGV.Rows.Count > 0 Then
                        Label4.Text = "Al buscar y encontrar el registro, puedes editar todo, excepto los Nombres."
                    End If
                End If
            End With
 
            ' buscar y retornar el índice de la fila a buscar 
            Dim fila As Integer = ds.Tables("Sujeto").DefaultView.Find(TextBox1.Text)
 
            ' si el índice es -1 no se encontró  
            If fila <> -1 Then
                b = True
                Editar.Enabled = True
                Eliminar.Enabled = True
                Registrar.Enabled = False
                With DGV
                    ' Establecer el índice de la primera fila del DataGridview para visualizarlo primero
                    .FirstDisplayedScrollingRowIndex = fila
                    .CurrentCell = .Rows(fila).Cells(0) 'Asignar la celda al CurrentCell para seleccionarla  
                    .Select() 'Seleccionar el control  
                End With
 
            Else
                MsgBox("No se pudo encontrar el registro!", vbInformation, "Buscar registro")
            End If
 
        Catch ex As Exception
            ex.Message.ToUpper()
        End Try
    End Sub
 
    'Editar
    Private Sub Editar_Click(sender As Object, e As EventArgs) Handles Editar.Click
        If TextBox1.Text <> "" And b = True Then
            If a = True Then
                DGV.ReadOnly = False
                Editar.Text = "Cancelar"
                Guardar.Enabled = True
                Buscar.Enabled = False
                Eliminar.Enabled = False
                Registrar.Enabled = False
                TextBox1.Enabled = False
                ComboBox1.Enabled = False
                a = False
            ElseIf a = False Then
                habilita()
                'Limpiamos para que no se repitan los datos
                ds.Clear()
                DGV.Refresh()
                cargar()
                a = True
                b = False
            End If
        End If
    End Sub
 
    'Actualizamos los datos 
    Private Sub Guardar_Click(sender As Object, e As EventArgs) Handles Guardar.Click
        Conexión1.ConnectionString = connString
        Conexión1.Open()
        '
        Dim row As DataGridViewRow = DGV.CurrentRow
        Dim str As String
 
        Convert.ToString(row.Cells("Nombres").Value)
 
 
        'Si buscamos por la clave
 
        If ComboBox1.Text = "Clave" Then
 
        End If
 
 
 
        str = "update [Sujeto] set [Nombres] = '" & Convert.ToString(row.Cells("Nombres").Value) & _
                            "' , [medidas] = '" & Convert.ToString(row.Cells("medidas").Value) & _
                                            "', [peso] = '" & Convert.ToString(row.Cells("peso").Value) & _
                                                            "', [long] = '" & Convert.ToString(row.Cells("long").Value) & _
                                                                            "', [sup] = '" & Convert.ToString(row.Cells("sup").Value) & _
                                                                                            "', [corp] = '" & Convert.ToString(row.Cells("corp").Value) & _
                                                                                                            "', [kam] = '" & Convert.ToString(row.Cells("kam").Value) & _
                                                                                                                            "', [prom] = '" & Convert.ToString(row.Cells("prom").Value) & _
                                                                                                                                            "', [manr] = '" & Convert.ToString(row.Cells("manr").Value) & _
                                                                                                                                                            "', [bau] = '" & Convert.ToString(row.Cells("bau").Value) & _
                                                                                                                                                                            "', [madd] = '" & Convert.ToString(row.Cells("madd").Value) & _
                                                                                                                                                                                            "', [peris] = '" & Convert.ToString(row.Cells("peris").Value) & _
                                                                                                                                                                                                            "', [fecha] = '" & Convert.ToString(row.Cells("fecha").Value) & "' Where [Clave] = '" & TextBox1.Text & "'"
        Dim cmd1 As OleDbCommand = New OleDbCommand(str, Conexión1)
        Try
            cmd1.ExecuteNonQuery()
        Catch ex As Exception
            MsgBox(ex.Message.ToUpper)
        End Try
 
 
        'Si se busco por el nombre
        If ComboBox1.Text = "Clave" Then
            str = "update [Sujeto] set [Nombres] = '" & Convert.ToString(row.Cells("Nombres").Value) & _
                                "' , [medidas] = '" & Convert.ToString(row.Cells("medidas").Value) & _
                                                "', [peso] = '" & Convert.ToString(row.Cells("peso").Value) & _
                                                                "', [long] = '" & Convert.ToString(row.Cells("long").Value) & _
                                                                                "', [sup] = '" & Convert.ToString(row.Cells("sup").Value) & _
                                                                                                "', [corp] = '" & Convert.ToString(row.Cells("corp").Value) & _
                                                                                                                "', [kam] = '" & Convert.ToString(row.Cells("kam").Value) & _
                                                                                                                                "', [prom] = '" & Convert.ToString(row.Cells("prom").Value) & _
                                                                                                                                                "', [manr] = '" & Convert.ToString(row.Cells("manr").Value) & _
                                                                                                                                                                "', [bau] = '" & Convert.ToString(row.Cells("bau").Value) & _
                                                                                                                                                                                "', [madd] = '" & Convert.ToString(row.Cells("madd").Value) & _
                                                                                                                                                                                                "', [peris] = '" & Convert.ToString(row.Cells("peris").Value) & _
                                                                                                                                                                                                                "', [fecha] = '" & Convert.ToString(row.Cells("fecha").Value) & "' Where [Clave] = '" & TextBox1.Text & "'"
 
 
        End If
        Conexión1.Close()
 
 
        Conexión1.Close()
 
        'Actualizamos
        ds.Clear()
        DGV.Refresh()
        cargar()
        Datas()
        comprueba()
        habilita()
 
        a = True
        b = False
    End Sub
 
    'Eliminamos el registro que se busco
    Private Sub Eliminar_Click(sender As Object, e As EventArgs) Handles Eliminar.Click
        If DGV.Rows.Count < 1 Then Exit Sub
 
        If MsgBox("Deseas eliminar el registro?", CType(vbQuestion + vbYesNo, MsgBoxStyle), _
                  "Eliminar registro") = vbNo Then Exit Sub
 
        Conexión1.ConnectionString = connString
        Conexión1.Open()
 
        Dim str As String
 
        str = "Delete from Sujeto Where Clave = '" & TextBox1.Text & "'"
        Dim cmd As OleDbCommand = New OleDbCommand(str, Conexión1)
        TextBox1.Text = ""
        Try
            cmd.ExecuteNonQuery()
            MsgBox("Registro eliminado", MsgBoxStyle.Exclamation, "Eliminar registro")
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        Conexión1.Close()
        'Actualizamos
        Actualizar()
    End Sub
 
    'Nos movemos al Form registro
    Private Sub Registrar_Click(sender As Object, e As EventArgs) Handles Registrar.Click
        Registro.Show()
        Me.Hide()
    End Sub
 
    'Actualizamos o restablecemos
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Actualizar()
    End Sub
 
    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Registro.Show()
        Me.Hide()
    End Sub
 
 
End Class



as
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
Val: 481
Bronce
Ha mantenido su posición en Visual Basic.NET (en relación al último mes)
Gráfica de Visual Basic.NET

ayuda no coinciden los tipos de datos en la expresión de criterios

Publicado por Miguel (476 intervenciones) el 14/12/2016 00:43:20
Los valores de los campos que estás enviando no corresponden a su tipo de datos en la db; recuerda que los números no llevan comillas.
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

ayuda no coinciden los tipos de datos en la expresión de criterios

Publicado por pabnoc (11 intervenciones) el 14/12/2016 10:03:48
un ejemplo amigo no entiendo bien tu respuesta....
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