影响sql查询到文本框的结果

问题描述 投票:-1回答:2

我正在使用sqlserver 2008和vb.net我试图影响我的文本框的SQL查询结果。这里是我试过的代码

  Dim rd As SqlDataReader
    Try
        Cn.Open()
        cmd = New SqlCommand("SELECT pk_veh, désignation, projet, version, [taille de lot] from [Cutting software].dbo.vehicule  WHERE désignation = '" & Form1.ComboBox3.SelectedValue & "'", Cn)
        rd = cmd.ExecuteReader
        While rd.Read
            imp.TextBox1.Text = rd.GetInt32("pk_veh")
            imp.TextBox2.Text = rd.GetString("désignation")
            imp.TextBox3.Text = rd.GetString("projet")
            imp.TextBox4.Text = rd.GetString("version")
            imp.TextBox5.Text = rd.GetInt32("[taille de lot]")
            imp.Show()
        End While
        Cn.Close()
    Catch ex As SqlException
        MessageBox.Show(ex.Message)
    End Try
End Sub

当我检查我的列的类型时,我总是有这个错误

System.InvalidCastException: 'La conversion de la chaîne "pk_veh" en type 'Integer' n'est pas valide.'FormatException: Input string was not in a correct format.

这里是我的列的类型

pk_veh,[批量大小]:int 名称,项目,版本:varchar [50]

vb.net sql-server-2008
2个回答
0
投票

当您尝试将不是有效Integer的内容转换为Integer时,会发生此错误。

在将其值转换为TextBox之前,请尝试检查字符串是否为DbNull,或尝试使用ISNULL(value, 0)以确保此列中没有任何空值。


0
投票

这里的解决方案

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim rd As SqlDataReader
    Try
        Cn.Open()
        Dim cmd As New SqlCommand("SELECT isnull(pk_veh,0)pk_veh, isnull(designation,'')designation, isnull(projet,'')projet, isnull(version,'')version, isnull(taille_de_lot,0)taille_de_lot from [Cutting software].dbo.vehicule  WHERE designation =  '" & Form1.ComboBox3.SelectedValue & "'", Cn)
        rd = cmd.ExecuteReader
        While rd.Read
            imp.TextBox1.Text = rd.GetInt32(0)
            imp.TextBox2.Text = rd.GetString(1)
            imp.TextBox3.Text = rd.GetString(2)
            imp.TextBox4.Text = rd.GetString(3)
            imp.TextBox5.Text = rd.GetInt32(4)
        End While
        Cn.Close()
    Catch ex As SqlException
        MessageBox.Show(ex.Message)
    End Try
    imp.Show()
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.