代码如下:
Private Sub Button5_Click(sender As Object, e As EventArgs)处理Button5。点击
con = New SqlConnection("Data Source=LAPTOP-16IIQENSSQLEXPRESS;Initial Catalog=students;Integrated Security=True")
con.Open()
cmd = New SqlCommand("select * from data where [Roll No.]=@[Roll No.]", con)
cmd.Parameters.Add("@Roll No.", SqlDbType.Int).Value = TextBox5.Text
Dim adp As New SqlDataAdapter(cmd)
Dim table As New DataTable()
adp.Fill(table)
If (table.Rows.Count() > 0) Then
DataGridView1.DataSource = table
TextBox2.Text = table.Rows(0)(0).ToString
TextBox1.Text = table.Rows(0)(1).ToString
TextBox3.Text = table.Rows(0)(2).ToString
TextBox4.Text = table.Rows(0)(3).ToString
Else
MessageBox.Show("No Data Found")
End If
End Sub
输入图片描述
您可以自由选择SQL参数的名称,它不需要匹配字段的名称。
因此,如果您调用参数@RollNo
而不是@Roll No.
(没有空格,没有点),则不再需要在SQL中转义名称,这应该可以解决当前的问题。
改变:
cmd = New SqlCommand("select * from data where [Roll No.]=@[Roll No.]", con)
cmd.Parameters.Add("@Roll No.", SqlDbType.Int).Value = TextBox5.Text
:
cmd = New SqlCommand("select * from data where [Roll No.]=@RollNo", con)
cmd.Parameters.Add("@RollNo", SqlDbType.Int).Value = TextBox5.Text