System.InvalidCastException: 'Operator' & 'is not defined for string "values (' 41611027," and type 'DataRowView'. '

0
        conexion.Open()
        Dim cmd As New SqlCommand()
        cmd.Connection = conexion
        Dim Agregar As String
        Dim fec As Date = Fecha.Value.ToString("yyyy-MM-dd")
        Dim fac As Date = FechaC.Value.ToString("yyyy-MM-dd")
        Agregar = "insert into cita (nCuenta, Categoria, Fecha, FechaC, Estado, Usuario)"
        Agregar += "values('" & nCuenta.Text & "," & Categoria.SelectedItem & "','" & fec & "','" & fac & "','" & Estado.SelectedItem
        Agregar += "','" & Usuario.Text & "')"
        cmd.CommandText = Agregar
        cmd.ExecuteNonQuery()
        MsgBox("Guardado Con Exito")
        Limpiar()
        conexion.Close()
    
asked by Mario 15.06.2017 в 05:03
source

1 answer

1

The problem with your query is that the SelectedItem property is not a string , but a DataRowView . First you must cast that property to its real type and then get the column you are interested in (in this example I use the 0, in your case the one you need)

On the other hand never generate your query using string concatenation. Use parameterized queries or your code will be exposed to SQL injection. Your code should be more or less like this:

'Convertimos los "SelectedItem" a su tipo real,DataRowView
Dim cat As DataRowView = TryCast(Categoria.SelectedItem, DataRowView)
Dim estad As DataRowView = TryCast(Estado.SelectedItem, DataRowView)

Agregar = "insert into cita (nCuenta, Categoria, Fecha, FechaC, Estado, Usuario)"
Agregar += " values(@nCuenta,@Categoria,@fecha,@fechac,@estado,@usuario)"
cmd.CommandText = Agregar
cmd.Parameters.Add("@nCuenta", SqlDbType.VarChar).Value = nCuenta.Text
cmd.Parameters.Add("@Categoria", SqlDbType.VarChar).Value = cat.Item(0).ToString()
cmd.Parameters.Add("@fecha", SqlDbType.DateTime).Value = fec
cmd.Parameters.Add("@fechac", SqlDbType.DateTime).Value = fac
cmd.Parameters.Add("@estado", SqlDbType.VarChar).Value = estad.Item(0).ToString()
cmd.Parameters.Add("@usuario", SqlDbType.VarChar).Value = Usuario.Text
cmd.ExecuteNonQuery()

There is another option. If in your ComboBox you set the ValueMember property, what you should do is replace SelectedItem with SelectedValue.ToString() .

    
answered by 15.06.2017 в 09:53