繁体   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