2013-03-14 66 views
0

我正在做一個表單,用戶正在寫他的用戶名並從按鈕列表中選擇。在插入之前,我需要檢查用戶名是否已經存在。服務器端代碼:Che重名和插入用戶vb.net

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 

因此,當用戶按下按鈕,它首先檢查重複的用戶名,如果一切正常,那麼它插入該行。 Btw錯誤發生時,我按下提交按鈕,它給了我Must declare the scalar variable "@cUserName".adapter.Fill(haha)線。

請我想知道我的代碼有什麼問題。幫我

在此先感謝。

回答

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) 
+0

我沒有得到它。你能否重新安排我的代碼,並把你的。我不知道我應該把你的線條放在哪裏。 – 7alhashmi 2013-03-14 05:52:13

+0

好吧,我知道該把它放在哪裏。但重複不起作用。我的意思是它不檢查用戶名是否存在。它只是添加所有用戶名。 – 7alhashmi 2013-03-14 05:58:59

1

您正在使用Parameter @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) 
+0

我沒有明白。你能否重新安排我的代碼,並把你的。我不知道我應該把你的線條放在哪裏。 – 7alhashmi 2013-03-14 05:54:44