简体   繁体   English

ASP.net在选择查询中使用label.Text

[英]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. 我必须使用标签中的文本值运行SQL查询,然后运行该查询并将数据绑定到gridview。 Here's my code in VB.net 这是我在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 ---> 我收到SqlCommand的以下错误消息--->

Object reference not set to an instance of an object.

Is the data binding for grid view correct? 网格视图的数据绑定是否正确?

Any ideas? 有任何想法吗?

1- This line will cause sql Injection in the future. 1-此行将在将来导致sql注入。

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.. 2-使用数据适配器时无需打开/关闭连接。

3- I think the error because you are initializing the Command in the class try move it to page load event. 3-我认为该错误是因为您正在初始化类中的Command,然后尝试将其移至页面加载事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM