0

I have to run a SQL query using a text value in a label and then run that query and bind data to a gridview. Here's my code in VB.net

Dim myConnection As SqlConnection = New SqlConnection

Dim ad As New SqlDataAdapter

Dim details As New DataSet

Dim detailcmd As New SqlCommand("select student_name,student_id from students where student_name = '" + snamelabel.Text + "'", myConnection)


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    ad.SelectCommand = detailcmd
    myConnection.ConnectionString = "Data Source=USER-PC\SQLEXPRESS;Initial  Catalog=students;Integrated Security=True"
    myConnection.Open()
    ad.Fill(details, "Details")
    myConnection.Close()

    DetailGridView.DataSource = details
    DetailGridView.DataBind()
End Sub

I get the following error message for the SqlCommand --->

Object reference not set to an instance of an object.

Is the data binding for grid view correct?

Any ideas?

1 Answer 1

1

1- This line will cause sql Injection in the future.

Dim detailcmd As New SqlCommand(
"select student_name,student_id from students where student_name = '"
 + snamelabel.Text + "'", myConnection)

2- No Need to open/close the connection when use data adapter..

3- I think the error because you are initializing the Command in the class try move it to page load event.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.