0

我正在做一个用户正在写他的用户名并从按钮列表中选择的表单。在插入之前,我需要检查用户名是否已经存在。服务器端代码为:

Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
    'Duplicate username
    Dim username As String = tbUsername.Text.Trim()
    Dim tempUser As Byte = CByte(rblDept.SelectedIndex)
    Dim query1 As String = "Select cUserName FROM Intranet.dbo.Gn_ISCoordinators WHERE cUserName = @cUserName"

    Dim haha As DataTable = New DataTable()
    Using adapter = New SqlDataAdapter(query1, ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
        adapter.Fill(haha)
        If haha.Rows.Count <> 0 Then
            lblmessage.Text = "Error! user name is already exist"
            Return
        End If
    End Using

    'Insert new user
    Dim query As String = "Insert into Intranet.dbo.Gn_ISCoordinators (cUserName,lDeptUser) Values ('" & username & "'," & tempUser & ")"
    Dim hehe As DataTable = New DataTable()
    Using adapter1 = New SqlDataAdapter(query, ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
        adapter1.Fill(hehe)
        lblmessage.Text = "User has been added"
    End Using
End Sub

因此,当用户按下按钮时,如果一切正常,它首先检查重复的用户名,然后插入该行。顺便说一句,当我按下提交按钮时会发生错误,它在线给了我Must declare the scalar variable "@cUserName".这个adapter.Fill(haha)

请我想知道我的代码有什么问题。帮我

提前致谢。

4

2 回答 2

1

您正在使用参数 @cUserName 但您没有对其进行初始化或将值传递给它。

Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
conn.Open()

Dim query1 As String = "Select cUserName FROM Intranet.dbo.Gn_ISCoordinators WHERE cUserName = @cUserName"

Dim command As New SqlCommand(query1, conn)
command.Parameters.AddWithValue("@cUserName",username)

Using adapter = New SqlDataAdapter(command)
于 2013-03-14T05:53:30.807 回答
1

错误消息显示了解决该问题所需知道的一切。您@cUserName在查询中使用了参数,但它从未设置过。

Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("IntranetConnectionString").ConnectionString)
conn.Open()

Dim query1 As String = "Select cUserName FROM Intranet.dbo.Gn_ISCoordinators WHERE cUserName = @cUserName"

Dim command As New SqlCommand(query1, conn )
Dim param As New SqlParameter()
param.ParameterName = "@cUserName"
param.Value = username 
command.Parameters.Add(param)

Using adapter = New SqlDataAdapter(command)
于 2013-03-14T05:39:35.253 回答