【问题标题】:ASP.net using label.Text in select queryASP.net 在选择查询中使用 label.Text
【发布时间】:2009-10-11 17:48:22
【问题描述】:

我必须使用标签中的文本值运行 SQL 查询,然后运行该查询并将数据绑定到网格视图。这是我在 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

我收到以下有关 SqlCommand 的错误消息 --->

Object reference not set to an instance of an object.

网格视图的数据绑定是否正确?

有什么想法吗?

【问题讨论】:

    标签: asp.net sql


    【解决方案1】:

    1-这行以后会导致sql Injection。

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

    2- 使用数据适配器时无需打开/关闭连接..

    3- 我认为错误是因为您在类中初始化命令尝试将其移动到页面加载事件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-06
      • 2012-09-19
      • 1970-01-01
      • 2021-11-01
      • 2016-10-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多