VB.NET中sqladapter.fill使用中出现异常..提示"列"无效.高手帮忙!
我写了一段小程序,发现在程序运行过程中,有异常错误,主要是按照几个字段来查询SQL数据库,combobox里包括字段:编号,姓名,国籍,业绩,加入时间...相对应在SQL中是bh,xm,gj,yj,joindata....各个字段的类型都设置为varchar类型,当使用"姓名"的时候就报错.说列名无效..希望高手帮忙解答!!谢谢 其中数据库表名为sales
原代码如下
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim id As String = TextBox1.Text
Dim di As String = ComboBox1.Text
Dim constring As String = "Data Source=6FFF157A3A3E49C;Initial Catalog=lzgdb;Integrated Security=True " '定义连接字符串
Dim sqlcon As New SqlClient.SqlConnection(constring) '定义连接
Dim r1 As String = "select * from sales where bh= " & id.ToString '定义combobox中选项的具体意义
Dim r2 As String = "select * from sales where xm= " & id.ToString
Dim r3 As String = "select * from sales where gj= " & id.ToString
Dim r4 As String = "select * from sales where yj= " & id.ToString
Dim r5 As String = "select * from sales where joindate= " & id.ToString
If di = " " Then
MessageBox.Show( "please change item! ")
Else
If id = " " Then
MessageBox.Show( "please input text! ")
End If
If di = "编号 " Then
Dim adapter As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter(r1, sqlcon)
Dim customers As DataSet = New DataSet
adapter.Fill(customers, "sales ")
DataGridView1.DataSource = customers
DataGridView1.DataMember = customers.Tables(0).TableName
Else
If di = "姓名 " Then
Dim adapter As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter(r2, sqlcon)
Dim customers As DataSet = New DataSet
'Dim returnvalue As Integer
adapter.Fill(customers, "sales ")
DataGridView1.DataSource = customers
DataGridView1.DataMember = customers.Tables(0).TableName
Else
If di = "国籍 " Then
Dim adapter As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter(r3, sqlcon)
Dim customers As DataSet = New DataSet
adapter.Fill(customers, "sales ")
DataGridView1.DataSource = customers
DataGridView1.DataMember = customers.Tables(0).TableName
Else
If di = "业绩 " Then
Dim adapter As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter(r4, sqlcon)
Dim customers As DataSet = New DataSet
adapter.Fill(customers, "sales ")
DataGridView1.DataSource = customers
DataGridView1.DataMember = customers.Tables(0).TableName
Else
If di = "加入日期 " Then
Dim adapter As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter(r5, sqlcon)
Dim customers As DataSet = New DataSet
adapter.Fill(customers, "sales ")
DataGridView1.DataSource = customers
DataGridView1.DataMember = customers.Tables(0).TableName
End If
End If
End If
End If
End If
End If
End Sub
[解决办法]
你的查询语句应该这样定义吧?
Dim r1 As String = "select * from sales where bh= ' " & id.ToString & " ' "
因为数据类型是VARCHAR的
[解决办法]
首先你的SQL查询语句语法寫的不對(如上樓所述);其次是你檢索的條件不對,如:
where bh= " & id.ToString,
xm= " & id.ToString,
gj= " & id.ToString,
......;
還有di既然是String型的,那判斷它相等就應該用.Equals();
最後當中那段代碼可以簡化,用Select Case... Case... End Select比較好