簡體   English   中英

更新或插入時返回gridview的PK(ASP.NET,C#)

[英]Returning PK of gridview when updating or inserting (ASP.NET, C#)

我需要對表的插入,更新和刪除等所有更改進行審核,並且我使用的是帶有自動生成的INSERT / UPDATE / DELETE語句的簡單SQLDataSource和GridView。 問題是,當更新一行時,我想獲取ID(主鍵)並將其放入審核表中-但是因為UPDATE查詢的唯一參數是實際數據而不是主鍵,所以我不知道如何訪問此信息。 這是我的UPDATE查詢:

InsertCommand="INSERT INTO [NominalCode] ([VAXCode], [Reference], [CostCentre], [Department], [ReportingCategory]) VALUES (@VAXCode, @Reference, @CostCentre, @Department, @ReportingCategory)" 

以下是審核的代碼:

protected void SqlDataSource1_Updating(object sender, SqlDataSourceCommandEventArgs e)
    {
        string fields = e.Command.Parameters[0].Value.ToString() + "," + e.Command.Parameters[1].Value.ToString() + "," + e.Command.Parameters[2].Value.ToString() + "," + e.Command.Parameters[3].Value.ToString() + "," + e.Command.Parameters[4].Value.ToString();
        System.Security.Principal.  WindowsPrincipal p = System.Threading.Thread.CurrentPrincipal as System.Security.Principal.WindowsPrincipal;
        string[] namearray = p.Identity.Name.Split('\\');
        string name = namearray[1];
        string queryString = "INSERT INTO Audit (source, action, item, userid, timestamp) VALUES (@source, @action, @item, @userid, @timestamp)";
        using (SqlConnection connection = new SqlConnection("con string removed for privacy"))
        {
            SqlCommand command = new SqlCommand(queryString, connection);
            command.Parameters.AddWithValue("@source", "Nominal");
            command.Parameters.AddWithValue("@action", "Update");
            command.Parameters.AddWithValue("@item", fields);
            command.Parameters.AddWithValue("@userid", name);
            command.Parameters.AddWithValue("@timestamp", DateTime.Now);
            connection.Open();
            try
            {
                command.ExecuteNonQuery();
            }
            catch (Exception x)
            {
                Response.Write(x);
            }
            finally
            {
                connection.Close();
            }
        }
    }

好吧,我覺得很蠢。 該ID當然位於SQL查詢的WHERE子句中! 由於某種原因,我粘貼了INSERT命令。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM