2012-06-24 47 views
1

我正在開發ASP.Net VB Web應用程序最近添加的記錄的標識和從gridview插入?

該應用程序包含一個GridView,它顯示我創建的datable中用戶表的記錄。該數據庫是一個Sql服務器數據庫。

下面插入數據的代碼爲一個表,並通過內置的功能@@Identity插入來自trainingTbl表中最近添加的記錄id(tt_id)和插入該記錄id到userAssessmentTbl。將標識添加到第二個userAssessmentTbl表中工作正常。

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) 
     Dim lblUsr2 As Control = FindControlRecursive(MultiTabs, "txtUsr") 
     Dim strQuery As String 
     Dim cmd As SqlCommand 

     strQuery = "Insert into trainingTbl(s_id, t_date, EditorId, wa_id, st_id) values(@s_id , @t_date, @EditorId, @wa_id, @st_id ) Insert into userAssessmentTbl(tt_id, UserId) values(@@Identity, @UserId)" 

     cmd = New SqlCommand(strQuery) 

     cmd.Parameters.AddWithValue("@s_id", DDLCourse.Text) 
     cmd.Parameters.AddWithValue("@t_date", Convert.ToDateTime(txtDate.Text)) 
     cmd.Parameters.AddWithValue("@EditorId", User.Identity.Name.ToString()) 
     cmd.Parameters.AddWithValue("@st_id", myLblStation.Value().ToString) 
     cmd.Parameters.AddWithValue("@wa_id", myLblWatch.Value().ToString) 
     cmd.Parameters.AddWithValue("@UserId", lblUsr2.UniqueID.ToString) 
     InsertUpdateData(cmd) 
    End Sub 

我有這個問題似乎我如何插入來自GridView一個uniqueidenifieruserAssessmentTbl數據庫爲中心!

以及如何使用循環,我可以將該GridView(GridView1)中的UserId記錄與來自@@Identity的循環ID一起插入userAssessmentTbl表中。

插入參數的這部分似乎是不正確的:

cmd.Parameters.AddWithValue("@UserId", lblUsr2.UniqueID().ToString) 

而且我遇到了錯誤的是:從字符串轉換爲uniqueidentifier時「轉換失敗。

我也試着這樣說:

cmd.Parameters.AddWithValue("@UserId", SqlDbType.UniqueIdentifier).Value().ToString() 

和IM會見了錯誤:'操作數類型衝突:INT與唯一標識符'

的qusetion有不兼容稍微改變爲如何插入一個字符串到SQL DB其中DataType是Uniqueidentifier?

任何幫助將非常感激。

回答

1

那麼首先:

@@IDENTITY returns the most recently created identity for your current connection, not necessarily the identity for the recently added row in a table. Always useSCOPE_IDENTITY()to return the identity of the recently added row.


其次,以asnwer你的問題:

SQL類型UniqueidentifierGuid CLR類型匹配。

因此,不需要將"@UserId"作爲參數傳入,您需要在字符串值之外創建Guid

Dim userID As Guid = New Guid(lblUsr2.UniqueID.ToString) 
+0

感謝您的答案的第一部分是偉大的,第二部分幫助我的方式。 – theBo