user187707
user187707

Reputation:

ASP.net using label.Text in select query

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?

Upvotes: 0

Views: 1691

Answers (1)

Wael Dalloul
Wael Dalloul

Reputation: 23024

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.

Upvotes: 1

Related Questions