2012-03-24 64 views
0

我有一個名爲db.mdb的ms-access數據庫,它包含各種表格。我使用ASP.NET和VB.NET創建帳戶創建頁面。ASP.NET - 使用自動增量輸入到MS-ACCESS中的VB.NET

我試圖在ms-acess數據庫中輸入頁面內的字段,但是當我打開數據庫時,儘管web開發沒有顯示任何錯誤,但沒有輸入值。

你能幫我嗎?

這是代碼:

Imports System.Data 
Imports System.Data.OleDb 
Imports System.Data.Odbc 



Partial Class _Default 
    Inherits System.Web.UI.Page 

    Protected Sub TextBox1_TextChanged(sender As Object, e As System.EventArgs) Handles txtName.TextChanged 

    End Sub 

    Protected Sub btnCreateAccount_Click(sender As Object, e As System.EventArgs) Handles btnCreateAccount.Click 

     Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Brian\Documents\Visual Studio 2010\WebSites\WebSite3\db.mdb;User Id=admin;Password=;") 

     Dim cmd As OleDbCommand = New OleDbCommand("INSERT INTO [USER] (UserName, UserSurname, Address, Country, TelNo, UserLogin, UserPassword, UserTypeID) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", conn) 




     If txtPass.Text = txtCPass.Text Then 

      conn.Open() 


      cmd.Parameters.Add("@UserName", OleDbType.VarChar, 255).Value = txtName.Text 
      cmd.Parameters.Add("@UserSurname", OleDbType.VarChar, 255).Value = txtSurname.Text 
      cmd.Parameters.Add("@Address", OleDbType.VarChar, 255).Value = txtUsername.Text 
      cmd.Parameters.Add("@Country", OleDbType.VarChar, 255).Value = txtCountry.Text 
      cmd.Parameters.Add("@TelNo", OleDbType.Integer).Value = txtTelNo.Text 
      cmd.Parameters.Add("@UserLogin", OleDbType.VarChar, 255).Value = txtUsername.Text 
      cmd.Parameters.Add("@UserPassword", OleDbType.VarChar, 255).Value = txtPass.Text 
      cmd.Parameters.Add("@UserTypeID", OleDbType.VarChar, 255).Value = "U" 





      cmd.ExecuteNonQuery() 

      conn.Close() 
      lblAccount.Visible = True 



     End If 

    End Sub 
End Class 

編輯:

所以我想在自動編號字段的用戶ID。它被設置爲來自訪問數據庫的自動編號。每當我嘗試從頁面輸入詳細信息到頁面時,它都不會允許我給出一個錯誤,即AutoNumber字段不能爲NULL。所以我加了一段代碼:

newID = Int32.Parse(cmd2.ExecuteScalar()) + 1 

所以,我從表列中獲取的最大數量和遞增1,然後與其他命令添加的。

cmd.Parameters.Add("@UserID", OleDbType.VarChar, 255).Value = newID 

但是它給了我一個錯誤說

Conversion from type 'DBNull' to type 'String' is not valid. 

回答

0

你還沒有打開調用cmd2.ExecuteScalar()函數之前的連接。而第一個參數是錯誤的。應該是@UserID而不是@Address。

conn.Open() 
newID = Int32.Parse(cmd2.ExecuteScalar()) + 1 
'Not sure what is column type (Varchar or Int) 
cmd.Parameters.Add("@UserID", OleDbType.Integer, 2).Value = newID 
... 
cmd.ExecuteNonQuery() 
conn.Close() 
+0

ahh好的謝謝。但現在它在這一行給我一個新的錯誤Dim cmd2 As OleDbCommand = new OleDbCommand(「SELECT MAX(UserID)FROM USER」,conn)'說'在'FROM' – Brian 2012-03-24 18:00:26

+0

嘗試錯誤 - SELECT MAX(UserID) FROM [USER] – 2012-03-24 18:01:36

+0

謝謝..雖然每個問題似乎都會導致另一個問題。我用新錯誤更新了該問題 – Brian 2012-03-24 18:09:55